问题
I wrote the toggle-accordion. It works good if links and accordion there are on one page, url links works. But how make open my toggle-accordion to url from another page?
https://codepen.io/malinosky/pen/wxKzEo
$(function(){
var accordionFaqHead = $('.i-accordionFaq-head');
accordionFaqHead.on('click', function() {
$(this).next().slideToggle();
});
function accHash() {
var hash = $(this).attr('href');
if (hash) {
var accordionItem = $(hash);
if (accordionItem.length) {
accordionItem.find('.i-accordionFaq-body').show();
}
}
}
$('.i-link-hash').on('click', accHash);
});
回答1:
You can check if there is hash
in the url
and call your function with it:
JS:
if (window.location.hash) {
var $hashedElement = $(window.location.hash);
accHash.apply($hashedElement);
}
Use apply
to call your function while setting this
to be equal to $hashedElement
To add hash while going from page to page you need to add it to your anchor tag first:
HTML:
<a href="myotherpage.html#item1"></a>
来源:https://stackoverflow.com/questions/51381825/how-open-my-toggle-accordion-from-another-page