Jquery 获取href值,然后将其作为id查找
我正在尝试基于锚导航构建此部分。当我点击一个链接时,我到达了所需的锚,点击的链接获得了一个具有特定样式的类,到目前为止,它运行良好: HTMLJquery 获取href值,然后将其作为id查找,jquery,anchor,Jquery,Anchor,我正在尝试基于锚导航构建此部分。当我点击一个链接时,我到达了所需的锚,点击的链接获得了一个具有特定样式的类,到目前为止,它运行良好: HTML <body> <nav> <div class="anchor-link" > <a href="#anchor1" > Anchor 1 </a> </div> <div class="anchor-link"> <a href="#anch
<body>
<nav>
<div class="anchor-link" > <a href="#anchor1" > Anchor 1 </a> </div>
<div class="anchor-link"> <a href="#anchor2"> Anchor 2 </a> </div>
<div class="anchor-link"> <a href="#anchor3"> Anchor 3 </a> </div>
<div class="anchor-link"> <a href="#anchor4"> Anchor 4 </a> </div>
<div class="anchor-link"> <a href="#anchor5"> Anchor 5 </a> </div>
</nav>
<div class="main-wrap">
<div id="anchor1"></div>
<div id="anchor2"></div>
<div id="anchor3"></div>
<div id="anchor4"></div>
<div id="anchor5"></div>
</div>
</body>
现在我想获取href中的值,但这不起作用,它返回未定义的值:
var href = $(this).attr('href');
console.log(href);
})
假设它起作用,并且var href保存单击链接的值,例如“#anchor1”,我如何继续在“main wrap”中查找id为“#anchor1”的div
这行得通吗?我该如何填写find查询
$(".main-wrap").find(...);
您正在尝试获取
的href
,但它没有该属性
将选择器更改为
或使用find()查看div内部
下面是一个JSFIDLE,它可以做您想做的事情: 还有jquery代码段:
$(document).ready(function(){
$(".anchor-link").on("click", function(){
$(this).addClass("active");
$(this).siblings().removeClass("active");
var href = $("a", this).attr('href');
$(href).html("You clicked " + href + " !");
});
});
如果您试图获取引用单击的
的$(this)
元素的href,则该元素没有任何href
属性
通过这样做:$(“a”,this).attr('href')
告诉您获取我刚才单击的div中
元素的href属性的值
在此之后,您可以使用
$(href)
选择相应的div,然后尝试以下单击处理程序
$(document).ready(function(){
$(".anchor-link a").on("click", function(){
$(this).parents('.anchor-link').addClass("active");
$(this).parents('.anchor-link').siblings().removeClass("active");
var href = $(this).attr('href');
console.log(href);
});
})
要正确获取href,请改为使用:
var href=$(“a”,this.attr('href')代码>
$(document).ready(function(){
$(".anchor-link").on("click", function(){
$(this).addClass("active");
$(this).siblings().removeClass("active");
var href = $("a", this).attr('href');
$(href).html("You clicked " + href + " !");
});
});
$(document).ready(function(){
$(".anchor-link a").on("click", function(){
$(this).parents('.anchor-link').addClass("active");
$(this).parents('.anchor-link').siblings().removeClass("active");
var href = $(this).attr('href');
console.log(href);
});
})