我正在建立一个网站。我想从ID链接到下一页。如下所示
网页名称: index.html
<a href="collection.html#rings">Rings</a>
网页名称: collection.html
<ul class="nav navbar-nav" id="nav">
<li id="rings" class="active"><a href="#">Rings</a></li>
<li id="earrings"><a href="#">Earrings</a></li>
<li id="neckwears"><a href="#" id="test1">Neckwear</a></li>
<li id="purses"><a href="#">Purses</a></li>
<li id="mini"><a href="#">Set an mini set</a></li>
</ul>
我尝试接受代码并在此实现,但没有取得任何成功。
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$(function(){
var current = location.pathname;
var url = window.location.hash;
$('#nav li').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
});
});
});
</script>
我想通过URL#值自动将活动类放在#nav列表中。
答案 0 :(得分:0)
您可以使用路径名作为选择器,如下所示:$('#nav li#'+current)
没有理由遍历所有这些。
$(document).ready(function() {
$(function() {
var current = "rings"; //location.pathname
$('#nav li#' + current).addClass("active");
});
});
&#13;
.active a {
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav navbar-nav" id="nav">
<li id="rings" class=""><a href="#">Rings</a></li>
<li id="earrings"><a href="#">Earrings</a></li>
<li id="neckwears"><a href="#" id="test1">Neckwear</a></li>
<li id="purses"><a href="#">Purses</a></li>
<li id="mini"><a href="#">Set an mini set</a></li>
</ul>
&#13;
答案 1 :(得分:0)
你只是在比较错误的变量。只需将您的代码更改为以下
即可
$(document).ready(function () {
$(function(){
var current = location.pathname;
var url = window.location.hash;
$('#nav li').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if("#" + $this.attr('id') == url){
$this.addClass('active');
}
});
});
});
&#13;