根据jQuery针对特定项目

Target specific item in Accordion with jQuery

本文关键字:项目 jQuery 根据      更新时间:2023-09-26

我想从另一个页面(例如page.html#secondItem)链接到手风琴中的特定面板。我已经读过我必须使用location.hash,但不确定在这个例子中如何使用。

有人能给我建议吗。

演示:http://jsbin.com/macamorasi/1/edit?html,css,js,输出

$(document).ready(function($) {
    $('#accordion').find('.accordion-toggle').click(function(){
      //Expand or collapse this panel
      $(this).next().slideToggle('fast');
      //Hide the other panels
      $(".accordion-content").not($(this).next()).slideUp('fast');
    });
  });
.accordion-toggle {cursor: pointer;}
  .accordion-content {display: none;}
  .accordion-content.default {display: block;}
<div id="accordion">
  <h4 class="accordion-toggle" id="firstItem">Accordion 1</h4>
  <div class="accordion-content default">
    <p>Cras malesuada ultrices augue molestie risus.</p>
  </div>
  <h4 class="accordion-toggle" id="secondItem">Accordion 2</h4>
  <div class="accordion-content">
    <p>Lorem ipsum dolor sit amet mauris eu turpis.</p>
  </div>
  <h4 class="accordion-toggle" id="thirdItem">Accordion 3</h4>
  <div class="accordion-content">
    <p>Vivamus facilisisnibh scelerisque laoreet.</p>
  </div>
</div>

http://jsbin.com/macamorasi/1/edit?html,css,js,输出

您可以检查location.hash是否存在。如果是,请使用它来查找感兴趣的元素,然后将其向下滑动。然后,您可以使用.siblings()查找其他<h4>元素,并获取它们的下一个邻居并将它们向上滑动。

$(document).ready(function($) {
  // General accordion click toggle
  $('#accordion').find('.accordion-toggle').click(function(){
    //Expand or collapse this panel
    $(this).next().slideToggle('fast');
    //Hide the other panels
    $(".accordion-content").not($(this).next()).slideUp('fast');
  });
  // Check for location hash
  if(location.hash) {
    // Remove the first '#' character
    var hash = location.hash.substr(1);
    // Expand element 
    if($('#'+hash).length) {
      $('#'+hash)
        .next()
          .slideDown()
          .end()
        .siblings('h4')
          .next()
          .slideUp();
    }
  }
});

请参阅此处的完整代码:http://jsbin.com/bonozoqezo/1/edit.要获得正确的演示,请使用哈希访问全屏演示:http://jsbin.com/bonozoqezo/1#secondItem