同时 打开 多 个 折叠 面板 , 如何 一 次 只 打开 一 个 JQuery 折叠 面板

ojsjcaue  于 2022-11-22  发布在  jQuery
关注(0)|答案(1)|浏览(170)

当前打开的可折叠面板在另一个可折叠面板打开时未关闭。
这是我用的代码,不知道哪里错了。

<script>
$(document).ready(function () {

//each accordion has a text entry and a corresponding image     
  var accordionEntries = document.querySelectorAll('.accordion-entry');
  var accordionImages = document.querySelectorAll('.accordion-image'); 
  
    for ( var i = 0; i < accordionEntries.length; i++ ) {
    accordionEntries[i].dataset.target = 'accordion-image-' + i;
    accordionImages[i].classList.add('accordion-image-' + i);
  }
  

//toggles accordion open state    
  $(document).on('click', '.accordion-header', function () {
    if ($(this).is(".accordion-open")) return $(this).removeClass("accordion-open");
    var parent = $(this).closest('.accordion-entry, .accordion-image');
    if(!parent.hasClass('.accordion-open')){
        parent.toggleClass('accordion-open');
      } else {
$('.accordion-open').removeClass('accordion-open')
}
    $('.' + parent.data('target')).toggleClass('accordion-open')
    
  })

})
</script>
t40tm48m

t40tm48m1#

感谢大家在回答这个问题时的帮助,一位同事最终帮助我解决了这个问题。以下是解决方案和评论,供其他人参考。

<script>
$(document).ready(function () { 
  var accordionEntries = document.querySelectorAll('.accordion-entry');
  var accordionImages = document.querySelectorAll('.accordion-image');
  
    for ( var i = 0; i < accordionEntries.length; i++ ) {
    accordionEntries[i].dataset.target = 'accordion-image-' + i;
    accordionImages[i].classList.add('accordion-image-' + i);
  }
      
  $(document).on('click', '.accordion-header', function () {
    // close currently opened accordion
    // add class to open clicked accordion  
    var accordionEntry = $(this).closest('.accordion-entry');
    var open = 'accordion-open';
    
    /* If the accordion that was clicked is in open state, 
    *  remove all occurrences of the 'accordion-open' class and DO NOTHING 
    *  AFTER.
    */
    if (accordionEntry.hasClass('accordion-open')) {
            accordionEntry.removeClass(open);
        $('.' + open).removeClass(open);
    } else {
        /* If the accordion that was clicked is NOT in open state, 
        *  remove all occurrences of the 'accordion-open' class and add 'accordion-open' class
        *. to the accordion that was clicked.
        */
        accordionEntry.removeClass(open);
                $('.'+ open).removeClass(open);
        accordionEntry.addClass('accordion-open');
        $('.'+ accordionEntry.data['target']).addClass(open)
          $('.'+ accordionEntry[0].dataset.target).addClass(open)
    } 
    });
}); 
</script>

相关问题