【问题标题】:how to iterate a result of jquery selector如何迭代jquery选择器的结果
【发布时间】:2013-07-17 00:49:13
【问题描述】:

我想迭代查询选择器的结果。

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]);

结果是标签ahref属性 我不知道为什么。

【问题讨论】:

  • 你想要什么输出?
  • 你可以使用.eachapi.jquery.com/each
  • @bohan 检查我的答案 ;)
  • @TusharGupta 我想获取第一个 DOM 对象但不是第一个对象的属性
  • 检查我的答案,我已经遍历了所有 a 标签

标签: javascript jquery loops jquery-selectors


【解决方案1】:

使用$.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

【讨论】:

  • 为什么$("#navigation &gt;a")[0];返回第一个标签的href属性而不是第一个dom对象
【解决方案2】:

如果要迭代所有&lt;a&gt;标签,可以使用每个函数

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

如果你只想获取第一个 &lt;a&gt; 标签,那么使用 .eq()

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

【讨论】:

  • 对于第一个&lt;a&gt;,有一个更简单的方法:$('#navigation &gt;a:first')
  • 但我想知道为什么$("#navigation &gt;a")[0];会返回第一个标签的href属性...
  • $("#navigation >a")[0] 返回 DOM 元素。不要使用 alert() 来查看它返回的内容,因为它只显示 href 属性。尝试在 Chrome 中使用检查元素或在 firefox 中使用 firebug。
【解决方案3】:

像这样使用first()

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

Reference

【讨论】:

  • 但我想迭代整个集合,而不仅仅是第一个。我想知道为什么$("#navigation &gt;a")[0];返回第一个标签的href属性。
  • 您的查询:“我想获取第一个 DOM 对象但不是第一个对象的属性”
【解决方案4】:

在 jQuery 中,当你使用像 [0] 这样的索引时,这意味着你正在访问 DOM 元素。这就是为什么

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

返回&lt;a&gt; 标签。

为了迭代一个 jQuery 选择器结果,使用 each

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

【讨论】:

    【解决方案5】:

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

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

    【讨论】:

      【解决方案6】:

      尝试使用

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-10
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        相关资源
        最近更新 更多