![](/img/trans.png)
[英]How to get href attribute of links and set it to href of next sibling using jquery?
[英]How to set id of next element into href attribute of link using jquery?
我必須立即將許多各自的id的值賦給許多html href
屬性(一個標記)。 使用我的代碼,我只會得到唯一的值(第一個)。 非常感謝。 朱里
$(".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>
遍歷所有具有類錨的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>
您需要所選元素的實例。 可以使用attr(attrName, function)
來做
$(".anchor").attr("href",function(){
return '#' + $(this).closest("div").next("div").attr("id");
});
使用jQuery each
OR循環(例如for
, while
等)對所有.anchor元素進行迭代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.