Javascript 如何使用jquery将下一个元素的id设置为链接的href属性?
我必须为许多htmlJavascript 如何使用jquery将下一个元素的id设置为链接的href属性?,javascript,jquery,html,attributes,href,Javascript,Jquery,Html,Attributes,Href,我必须为许多htmlhref属性(一个标记)分配紧跟其后的各自id的值。 在我的代码中,我只得到一个值(第一个)。 非常感谢。 朱丽 $(“.anchor”).attr(“href”,“#”+($(“.anchor”).closest(“div”).next(“div”).attr(“id”) 得到锚1 段落 得到锚2 另一段 Jquery在第二个参数中使用函数,迭代所选元素并更改其属性。也可以使用.parent()而不是.closest(“div”) $(“.anchor”).attr(
href
属性(一个标记)分配紧跟其后的各自id的值。
在我的代码中,我只得到一个值(第一个)。
非常感谢。
朱丽
$(“.anchor”).attr(“href”,“#”+($(“.anchor”).closest(“div”).next(“div”).attr(“id”)代码>
得到锚1
段落
得到锚2
另一段
Jquery在第二个参数中使用函数,迭代所选元素并更改其属性。也可以使用.parent()
而不是.closest(“div”)
$(“.anchor”).attr(“href”,function(){
返回“#”+$(this.parent().next(“div”).attr(“id”);
});代码>
得到锚1
段落
得到锚2
另一段
在所有具有类锚点的a标记中迭代循环,并使用$(this).parent(“div”).next(“div”).attr(“id”)
选择器获取a标记的链接
请检查下面的代码片段
$(“.anchor”)。每个(函数(){
$(this.attr(“href”),“#”+($(this.parent(“div”).next(“div”).attr(“id”));
});代码>
得到锚1
段落
得到锚2
另一段
您需要所选元素的实例。你能用它吗
使用jQueryeach
或任何类似for
、while
等循环来迭代所有.anchor元素。问题解决了吗?@Mohammad是的,非常感谢,你们都是最好的
$(".anchor").attr("href",function(){
return '#' + $(this).closest("div").next("div").attr("id");
});