Нажатие кнопки Влияет на все Кнопки

#jquery

#jquery

Вопрос:

У меня есть кнопка открытия и закрытия jQuery, которая показывает текст при нажатии. Моя возможность для улучшения заключается в том, что всякий раз, когда я нажимаю кнопку, активируются другие, а не только та, которую я хочу. Я немного новичок в jQuery. Любая помощь приветствуется. Как вы можете видеть на рисунке, нажатие на одну кнопку открывает обе, когда я хочу, чтобы открылась только эта кнопка.

скриншот

JS:

 var toggler = $('.js_toggler'),
  box = $('.customer-grid');

toggler.on('click', function(ev) {
ev.preventDefault;

if ( !toggler.data('active') ) {
  // If toggler is not active

  toggler
    .addClass('is-active');

  setTimeout(function() { 
    toggler
      .data('active', '1');
    box.addClass('is-active');
  }, 100);
} else {
  // If toggler is already active

  box.removeClass('is-active');

  toggler
    .removeClass('is-active');

  setTimeout(function() {
    toggler
      .removeData('active');
  }, 100);
}
});
  

HTML /PHP:

 <section class="procurement">
<p class="date">Period of Perfomrance: <?php echo esc_html( $date ); ?></p>
<p class="title"><?php echo esc_html( $heading ); ?></p>
<button class="toggler js_toggler"> </button>
<p class="date"><?php echo strtoupper( $unqiue_id ); ?></p>

<p class="special">Special Item Numbers:</p>

<div class="customer-grid">
    <section class="number">
        <p class="item"><?php echo esc_html( $special_item_one ); ?></p>
        <p class="value"><?php echo esc_html( $special_item_one_value ); ?></p>
    </section>
  

CSS:

 .customer-grid {
    display: none;

  amp;.is-active {
    display: block;
  }
}
  

Ответ №1:

Удалите переменные toggler и box , переместите селектор в начало click обработчика событий и используйте this с относительной поперечностью, чтобы получить связанные .customer-grid

 $('.js_toggler').on('click', function(ev) {
  ev.preventDefault;

  var box = $(this).closest("section").find('.customer-grid');

  if (!this.data('active')) {
    // If this is not active

    this.addClass('is-active');

    setTimeout(function() {
      this.data('active', '1');
      box.addClass('is-active');
    }, 100);
  } else {
    // If this is already active

    box.removeClass('is-active');

    this.removeClass('is-active');

    setTimeout(function() {
      this.removeData('active');
    }, 100);
  }
});