问题
Is this possible using jQuery/javascript?
In another page, I have a <nav>
that are just tabs and shows only a specific content when you click a tab-link
.
page1.html:
<nav class="subPageNav">
<a href="#" id="A" class="tab-link">A</a>
<a href="#" id="B" class="tab-link">B</a>
<a href="#" id="C" class="tab-link">C</a>
<a href="#" id="D" class="tab-link">D</a>
</nav>
<section id="A">
<!-- content -->
</section>
<section id="B">
<!-- content -->
</section>
and so on..
In a separate page, I have an <a>
where I should be sent to the specific tab from another page.
page2.html
<a href="next.html#A">A</a>
The code I had isn't working as I wanted. How can I pull off this?
回答1:
You need to get the hash in the URL, find the corresponding element and then trigger a click:
$(function() {
var activeTab = document.querySelector(location.hash);
if (activeTab) {
activeTab.click();
}
});
回答2:
Try this:
$(document).ready( function() {
var activeTab = window.location.hash;
if (activeTab) {
$( activeTab )[0].click();
}
});
回答3:
This one worked out for me. I added id
to the <a>
buttons.
page1.html
<a id="nav-a" href="page2.html">A</a>
<a id="nav-b" href="page2.html">B</a>
<a id="nav-c" href="page2.html">C</a>
<a id="nav-d" href="page2.html">D</a>
then create a javascript file with this
$(function() {
$('a#nav-a').click(function(event) {
localStorage.setItem("text", "nav-a");
});
$('a#nav-b').click(function(event) {
localStorage.setItem("text", "nav-b");
});
/*and so on...*/
var path = window.location.pathname;
var pathSub = path.substring(path.lastIndexOf("/") + 1, path.length)
if(pathSub == "page2.html"){
document.getElementById(localStorage.getItem('text')).click();
}
})
and for the page2.html, I include the id
the same as the id
of the <a>
elements.
<nav class="subPageNav">
<a href="#" id="nav-a" class="tab-link">A</a>
<a href="#" id="nav-b" class="tab-link">B</a>
<a href="#" id="nav-c" class="tab-link">C</a>
<a href="#" id="nav-d" class="tab-link">D</a>
</nav>
回答4:
What you need to do is use a partially full URL:
<a href="/next.html#A">A</a>
Try using this - all that changed is the /
at the start.
来源:https://stackoverflow.com/questions/52509059/link-redirect-to-another-page-and-specific-tab