JQuery показать / скрыть, избегая конфликтов в нескольких группах - PullRequest
1 голос
/ 09 января 2020

У меня есть простая навигация, которая показывает / скрывает div и добавляет / удаляет класс активных объектов для навигации. Это работает хорошо, но если у меня есть похожие разделы на моей странице, они конфликтуют (щелкнув ссылку в первой навигационной панели, можно скрыть элементы div и в других разделах.

Как я могу иметь несколько экземпляров разделов отображения / скрытия без данных -группа a 'конфликтующая с' группой данных b '?

Моя HTML:

<section class="show-hiders" data-group="a">
    <div class="col-md-6">

        <ul class="nav nav-pills">
            <li class="active"><a href="" data-related="1">Subject 1</a></li>
            <li><a href="" data-related="2">Subject 2</a></li>
            <li><a href="" data-related="3">Subject 3</a></li>
        </ul>

      <div  class="show-hider show-first" data-id="1">
        <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic1" alt="" />
      </div>
      <div  class="show-hider" data-id="2">
          <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic2" alt="" />
      </div>
      <div  class="show-hider" data-id="3">
        <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic3" alt="" />
      </div>
    </div>

    <div class="col-md-6">
          <div class="show-hider show-first" data-id="1">
            <p>Text content 1</p> 
          </div>
          <div class="show-hider" data-id="2">
             <p>Text content 2</p>   
          </div>
          <div class="show-hider" data-id="3">
            <p>Text content 3</p> 
          </div>
    </div>
</section>

<section class="show-hiders" data-group="b">
    <div class="col-md-6">

        <ul class="nav nav-pills">
            <li class="active"><a href="" data-related="4">Subject 4</a></li>
            <li><a href="" data-related="5">Subject 5</a></li>
            <li><a href="" data-related="6">Subject 6</a></li>
        </ul>

      <div  class="show-hider show-first" data-id="4">
        <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic4" alt="" />
      </div>
      <div  class="show-hider" data-id="5">
          <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic5" alt="" />
      </div>
      <div  class="show-hider" data-id="6">
        <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic6" alt="" />
      </div>
    </div>

    <div class="col-md-6">
          <div class="show-hider show-first" data-id="4">
            <p>Text content 4</p> 
          </div>
          <div class="show-hider" data-id="5">
             <p>Text content 5</p>   
          </div>
          <div class="show-hider" data-id="6">
            <p>Text content 6</p> 
          </div>
    </div>
</section>

Моя jQuery:

//SHOW-HIDERS
$(".show-hider").each(function(){
     $(this).hide();
    if($(this).attr('class') == 'show-hider show-first') {
        $(this).show();
    }
});

$('.show-hiders .nav a').on( "click", function(e) {
    e.preventDefault();
    var id = $(this).attr('data-related'); 
    $(".show-hider").each(function(){
        $(this).hide();
        if($(this).attr('data-id') == id) {
            $(this).show();
        }
    });
});

$('.show-hiders .nav li').on('click', function(){
    $(this).siblings().removeClass('active')
    $(this).addClass('active');
})

1 Ответ

0 голосов
/ 09 января 2020

Вы можете использовать .closest(), чтобы найти ближайший восходящий элемент, чтобы найти, в каком <section> вы находитесь. Если вы затем сохраните этот выбор, вы можете использовать .find() вместе с другими вашими селекторами, чтобы убедиться, что вы будете искать только в этом <section>

//SHOW-HIDERS
$(".show-hider").each(function() {
  $(this).hide();

  if ($(this).attr('class') == 'show-hider show-first') {
    $(this).show();
  }
});

$('.show-hiders .nav a').on("click", function(e) {
  e.preventDefault();
  // Return the <section> element that we're in
  const $group = $(this).closest('section[data-group]');
  let id = $(this).attr('data-related');
  
  // Find the '.show-hider' elements within the <section>
  $group.find(".show-hider").each(function() {
    $(this).hide();
    
    if ($(this).attr('data-id') == id) {
      $(this).show();
    }
  });
});

$('.show-hiders .nav li').on('click', function() {
  $(this).siblings().removeClass('active')
  $(this).addClass('active');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="show-hiders" data-group="a">
  <div class="col-md-6">

    <ul class="nav nav-pills">
      <li class="active"><a href="" data-related="1">Subject 1</a></li>
      <li><a href="" data-related="2">Subject 2</a></li>
      <li><a href="" data-related="3">Subject 3</a></li>
    </ul>

    <div class="show-hider show-first" data-id="1">
      <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic1" alt="" />
    </div>
    <div class="show-hider" data-id="2">
      <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic2" alt="" />
    </div>
    <div class="show-hider" data-id="3">
      <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic3" alt="" />
    </div>
  </div>

  <div class="col-md-6">
    <div class="show-hider show-first" data-id="1">
      <p>Text content 1</p>
    </div>
    <div class="show-hider" data-id="2">
      <p>Text content 2</p>
    </div>
    <div class="show-hider" data-id="3">
      <p>Text content 3</p>
    </div>
  </div>
</section>

<div>DEMO</div>
<div>DEMO</div>
<div>DEMO</div>

<section class="show-hiders" data-group="b">
  <div class="col-md-6">

    <ul class="nav nav-pills">
      <li class="active"><a href="" data-related="4">Subject 4</a></li>
      <li><a href="" data-related="5">Subject 5</a></li>
      <li><a href="" data-related="6">Subject 6</a></li>
    </ul>

    <div class="show-hider show-first" data-id="4">
      <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic4" alt="" />
    </div>
    <div class="show-hider" data-id="5">
      <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic5" alt="" />
    </div>
    <div class="show-hider" data-id="6">
      <img class="img-responsive" src="https://via.placeholder.com/600x350?text=pic6" alt="" />
    </div>
  </div>

  <div class="col-md-6">
    <div class="show-hider show-first" data-id="4">
      <p>Text content 4</p>
    </div>
    <div class="show-hider" data-id="5">
      <p>Text content 5</p>
    </div>
    <div class="show-hider" data-id="6">
      <p>Text content 6</p>
    </div>
  </div>
</section>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...