[英]Open element in Accordion based on ID - jQuery
I have a simple jQuery Accordion on my website. 我的网站上有一个简单的jQuery手风琴 。
Within each element, there are <span>
elements with unique IDs. 在每个元素中,都有具有唯一ID的<span>
元素。
So... if I click /gallery#football
it should open the 2nd block in my Accordion. 所以...如果我单击/gallery#football
则应该打开我的手风琴中的第二块。
Is this possible? 这可能吗?
My Fiddle is here . 我的小提琴在这里 。
Javascript 使用Javascript
(function($) {
var allPanels = $('.accordion > dd').hide();
var allLinks = $('a.heading');
$('.accordion > dt > a').click(function() {
allPanels.slideUp();
//Remove all
allLinks.removeClass('active');
if ($(this).parent().next().is(":visible")) return false;
$(this).parent().next().slideDown();
//Add active class
$(this).addClass('active');
return false;
});
$('.accordion > dt > a').first().trigger('click');
})(jQuery);
HTML HTML
<dl class="accordion">
<dt><a href="" class="heading">Tester</a></dt>
<dd>
<span id="tester"></span>
<span id="anothertester"></span>
<p>bla</p>
</dd>
<dt><a href="" class="heading">Sports</a></dt>
<dd>
<span id="football"></span>
<span id="basketball"></span>
<p>bla</p>
</dd>
</dl>
You use the find()
and parent()
or closest()
functions: 您可以使用find()
和parent()
或closest()
函数:
// Get id from url
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('#')); // This will give you #football
var spanTag = $('.accordion').find(id); //#football span tag
var parentTag = spanTag.closest('dd');
//open the accordion
...
The best way is to create a new function for this: 最好的方法是为此创建一个新函数:
function setAccordion() {
// Get id from url
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('#')); // This will give you #football
var spanTag = $('.accordion').find(id); //#football span tag
var parentTag = spanTag.closest('dd');
//open the accordion
...
}
// Call the function
setAccordion();
Working DEMO in jsfiddle: 在jsfiddle中工作的DEMO:
You can test it also to change the #football
id by eg #tester
, which opens the first accordion. 您也可以通过#tester
对其进行测试,以更改#football
ID,这将打开第一个手风琴。
http://jsfiddle.net/2hmzcgqm/11/ http://jsfiddle.net/2hmzcgqm/11/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.