jQuery 如何迭代jquery选择器的结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17717205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:48:53  来源:igfitidea点击:

how to iterate a result of jquery selector

javascriptjqueryloopsjquery-selectors

提问by bohan

I want to iterate a result of query selector.

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

Html code

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>

when I use javascript

当我使用 javascript

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

the result is the tag ahref attribute I don't know why.

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

回答by Sushanth --

Use $.each

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

回答by EpokK

Use first()like this:

first()像这样使用:

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

Reference

参考

回答by Setrákus Ra

If you want to iterate all <a>tags, you can use each function

如果要迭代所有<a>标签,可以使用每个函数

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

and if you only want to get the first <a>tag then use .eq()

如果您只想获取第一个<a>标签,请使用 .eq()

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

回答by U.P

In jQuery, when you use index like [0], it means you are access the DOM element. That is why

在 jQuery 中,当您使用 index like 时[0],意味着您正在访问 DOM 元素。这就是为什么

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

returns <a>tag.

返回<a>标签。

In order to iterate a jQuery selector result, use each

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

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

回答by frogatto

You can use jQuery built-in each()for this iteration like this:

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

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

回答by Jonas Grumann

Try using

尝试使用

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

instead, so you can see all the results in the console ( cmd + alt + i in chrome)

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