您好,我正在尝试在用户单击导航项后选择它们,并且在页面加载后它们应该保持选中状态。我尝试了很多例子,但没有一个对我有用。
这是标题中的内容。
<nav id="navigation">
<ul id = "nav-ul">
<li><a href="<?php echo $this->base?>/Logins/index">item1</a></li>
<li> <a href="<?php echo $this->base?>/Logins/item2">item2</a></li>
<li><a href="<?php echo $this->base?>/Logins/item3">item3</a></li>
</ul>
</nav>
这是我在 script.js 中的内容。所有文件中都添加了脚本。
我试过的最后一个
$(document).ready(function(){
$('#navigation ul li a').each(function(index) {
if(this.href.trim() == window.location)
$(this).addClass("selected");
});
});
比试过这个
$(document).ready(function(){
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$("#navigation ul li a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("active");
$("#navigation ul li a").selected
})
});
似乎没有任何效果。
最佳答案
这是你的标记
<ul id = "nav-ul">
<li><a href="<?php echo $this->base?>/Logins/index" >item1</a></li>
<li> <a href="<?php echo $this->base?>/Logins/item2" >item2</a></li>
<li><a href="<?php echo $this->base?>/Logins/item3" >item3</a></li>
然后
获取文件名
filename = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
然后通过jquery找到 anchor 标签
$("a[href$="+filename +"]").addClass("selected")
希望对你有帮助
关于javascript - Jquery 自动选择菜单项。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24207208/