这是我第一次做这样的事情。
假设在我的 HTML 文件中我有类似的东西
<div class="main_tabs">
<ul class="tabs">
<li id="home_tab"><a href="index.html">Home</a></li>
<li id="other_tab"><a href="other.html">Other</a></li>
</ul>
</div>
然后在我的 JavaScript 文件中有类似
的内容jQuery(document).ready(function() {
jQuery('.main_tabs .tabs a').on('click', function(e) {
e.preventDefault();
switch(this.id){
case "home_tab":
window.location.href = "index.html";
break;
case "other_tab":
window.location.href = "other.html";
break;
}
});
});
当我单击选项卡时,没有任何反应。我尝试了很多不同的东西,但我无法让它工作。任何人都可以帮助我(顺便说一下,我需要保留 preventDefault 来做函数中的其他一些事情,所以我需要手动进行页面更改)?
最佳答案
您需要获取 id
或父级 li
因为 a
标签没有 id
属性.
jQuery(document).ready(function() {
jQuery('.main_tabs .tabs a').on('click', function(e) {
e.preventDefault();
switch (this.parentNode.id) {
// -----^-- get parent node and it's id
case "home_tab":
window.location.href = "index.html";
break;
case "other_tab":
window.location.href = "other.html";
break;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="main_tabs">
<ul class="tabs">
<li id="home_tab"><a href="index.html">Home</a>
</li>
<li id="other_tab"><a href="other.html">Other</a>
</li>
</ul>
</div>
关于javascript - 使用选项卡导航到不同的 html 文件(HTML、JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37018519/