如何使用 jquery 将下一个元素的 id 设置为 link 的 href 属性?

How to set id of next element into href attribute of link using jquery?

我必须为许多 html href 属性(标签)分配紧随其后的各自 ID 的值。 使用我的代码,我只得到一个值(第一个)。 非常感谢。 树里

$(".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>

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>

遍历所有具有 class 锚点的 a 标签并使用 $(this).parent("div").next("div").attr("id")) 选择器为 a 标签获取 link。

请检查以下代码段。

$(".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>

您需要所选元素的实例。可以用attr(attrName, function)来做

$(".anchor").attr("href",function(){
    return '#' + $(this).closest("div").next("div").attr("id");
});

使用 jQuery eachforwhile 等任何循环来迭代所有 .anchor 元素。