簡體   English   中英

如何使用jQuery將下一個元素的ID設置為鏈接的href屬性?

[英]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循環(例如forwhile等)對所有.anchor元素進行迭代。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM