问题
I'm trying to add deep linking to the code below so I can link directly to an accoridon item and open it when I enter the correct URL into the address bar:
Here's my working accordion WITHOUT deep linking:
$('.responsive-accordion').each(function() {
// Set Expand/Collapse Icons
$('.responsive-accordion-minus', this).hide();
// Hide panels
$('.responsive-accordion-panel', this).hide();
// Bind the click event handler
$('.responsive-accordion-head', this).click(function(e) {
// Get elements
var thisAccordion = $(this).parent().parent(),
thisHead = $(this),
thisPlus = thisHead.find('.responsive-accordion-plus'),
thisMinus = thisHead.find('.responsive-accordion-minus'),
thisPanel = thisHead.siblings('.responsive-accordion-panel');
// Reset all plus/mins symbols on all headers
thisAccordion.find('.responsive-accordion-plus').show();
thisAccordion.find('.responsive-accordion-minus').hide();
// Reset all head/panels active statuses except for current
thisAccordion.find('.responsive-accordion-head').not(this).removeClass('active');
thisAccordion.find('.responsive-accordion-panel').not(this).removeClass('active').slideUp();
// Toggle current head/panel active statuses
if (thisHead.hasClass('active')) {
thisHead.removeClass('active');
thisPlus.show();
thisMinus.hide();
thisPanel.removeClass('active').slideUp();
} else {
thisHead.addClass('active');
thisPlus.hide();
thisMinus.show();
thisPanel.addClass('active').slideDown();
}
});
});
I have been trying to integrate this piece of code to initiate deep linking but it just isn't working:
var active = 1;
var hash = document.location.hash;
if (hash.length > 0) {
var section = $("#deep-link").find("> li" + hash);
if (section.length) {
active = section.index();
}
thisPanel.addClass('active').slideDown();
}
HTML is a simple UL:
<ul class="responsive-accordion responsive-accordion-default bm-larger" id="deep-link">
<li id="item-0">
<div class="responsive-accordion-head">
Heading Here
</div>
<div class="responsive-accordion-panel">
Content here
</div>
</li>
</ul>
回答1:
I think there is no setted thisPanel variable in your function. This should work for you.
var active = 1;
var hash = document.location.hash;
if (hash.length > 0) {
var section = $("#deep-link").children("li" + hash);
var thisPanel = section.children(".responsive-accordion-panel");
if (section.length) {
active = section.index();
}
thisPanel.addClass('active').slideDown();
}
来源:https://stackoverflow.com/questions/31727657/deep-link-and-open-an-accordion-item