我必须为许多html href
属性(标签)分配紧跟其后的各自id的值。使用我的代码,我只得到一个唯一的值(第一个)。非常感谢。Juri
$(".anchor").attr("href","#"+($(".anchor").closest("div").next("div").attr("id")));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a class="anchor">Get anchor 1</a>
</div>
<div id="link1">
<p>A paragraph</p>
</div>
<div>
<a class="anchor">Get anchor 2</a>
</div>
<div id="link2">
<p>Another paragraph</p>
</div>
发布于 2016-09-26 19:55:09
在第二个参数中带有函数的Jquery .attr()
,迭代选定的元素并更改其属性。另外,请使用.parent()
而不是.closest("div")
$(".anchor").attr("href", function(){
return "#"+$(this).parent().next("div").attr("id");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a class="anchor">Get anchor 1</a>
</div>
<div id="link1">
<p>A paragraph</p>
</div>
<div>
<a class="anchor">Get anchor 2</a>
</div>
<div id="link2">
<p>Another paragraph</p>
</div>
发布于 2016-09-26 19:55:43
您需要所选元素的实例。我可以使用attr(attrName, function)
来做这件事
$(".anchor").attr("href",function(){
return '#' + $(this).closest("div").next("div").attr("id");
});
发布于 2016-09-26 19:55:32
循环遍历所有具有类锚点的a标记,并使用$(this).parent("div").next("div").attr("id"))
选择器获取a标记的链接。
请检查下面的代码片段。
$(".anchor").each(function(){
$(this).attr("href","#"+($(this).parent("div").next("div").attr("id")));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><a class="anchor">Get anchor 1</a>
</div>
<div id="link1">
<p>A paragraph</p>
</div>
<div><a class="anchor">Get anchor 2</a>
</div>
<div id="link2">
<p>Another paragraph</p>
</div>
https://stackoverflow.com/questions/39702105
复制相似问题