簡體   English   中英

如何迭代jquery選擇器的結果

[英]how to iterate a result of jquery selector

我想迭代查詢選擇器的結果。

Html代碼

<nav id="navigation">
        <a href="#" tabindex="1" class="active_nav">nav1</a>
        <a href="#" tabindex="2">nav2</a>
        <a href="#"tabindex="3">nav3</a>
</nav>

當我使用javascript

alert($("#navigation >a")[0]);

結果是標簽a href屬性我不知道為什么。

使用$.each

$("#navigation > a").each(function() {

     console.log(this.href)
});

$('#navigation > a')[0]
      ^              ^---- Selects the 1st dom object from the jQuery object
      |                    that is nothing but the index of the element among 
      |                    the list of elements
      |-------  Gives you children of nav(3 anchor tags in this case)  which is a
                jQuery object that contains the list of matched elements

像這樣使用first()

var element = $("#navigation>a").first();
console.log(element);

參考

如果要迭代所有<a>標記,可以使用每個函數

$('#navigation >a').each(function() { 
    alert(this.href);
});

如果你只想獲得第一個<a>標簽,那么使用.eq()

alert($('#navigation >a').eq(0).attr('href');

在jQuery中,當您使用像[0]這樣的索引時,這意味着您正在訪問DOM元素。 這就是為什么

$("#navigation >a")[0]

返回<a>標簽。

為了迭代jQuery選擇器結果,請使用每個

$("#navigation >a").each(function(index, elem){
});

您可以使用jQuery內置each()進行此迭代,如下所示:

$("#navigation>a").each(function(index){
    console.log("I am " + index + "th element.");
    //and you can access this element by $(this)
});

嘗試使用

console.log($("#navigation >a"))

相反,所以你可以在控制台中看到所有結果(cmd + alt + i in chrome)

暫無
暫無

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

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