我想迭代查询选择器的结果。
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属性
我不知道为什么。
答案 0 :(得分:21)
使用$.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
答案 1 :(得分:3)
答案 2 :(得分:2)
如果要迭代所有<a>
标记,可以使用每个函数
$('#navigation >a').each(function() {
alert(this.href);
});
如果您只想获得第一个<a>
标记,请使用.eq()
alert($('#navigation >a').eq(0).attr('href');
答案 3 :(得分:1)
在jQuery中,当您使用[0]
之类的索引时,这意味着您正在访问DOM元素。这就是为什么
$("#navigation >a")[0]
返回<a>
代码。
为了迭代jQuery选择器结果,请使用每个
$("#navigation >a").each(function(index, elem){
});
答案 4 :(得分:1)
您可以使用jQuery内置each()
进行此迭代,如下所示:
$("#navigation>a").each(function(index){
console.log("I am " + index + "th element.");
//and you can access this element by $(this)
});
答案 5 :(得分:-1)
尝试使用
console.log($("#navigation >a"))
相反,您可以在控制台中看到所有结果(cmd + alt + i in chrome)