2013-07-18 9 views
11

クエリセレクタの結果を反復したい。jqueryセレクタの結果を反復する方法

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属性 です。

+1

:あなただけのように使用first()

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

+0

あなたは '.each'を使用することができますhttp://api.jquery.com/each/ –

+0

@ボハン私の答えをチェック;) – EpokK

答えて

14

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

が必要なのはなぜでしょうか?最初のDOMオブジェクトではない最初のタグの属性 – bohan

0

コンソールですべての結果を見ることができますので、代わりに

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

を使用してみてください(CMDクロムで+ ALT + I)

1

jQueryでは、インデックスは[0]のように、あなたがDOM要素にアクセスしていることを意味します。だからこそ

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

返信<a>タグです。 jQueryのセレクタの結果を反復処理するために

、あなたはこのように、この反復のため、内蔵each()のjQueryを使用することができ、各

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

使用:あなたはすべての<a>を反復処理したい場合は

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

をタグを使用すると、各機能を使用できます。

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

あなたが欲しいものを出力

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

Reference

+1

$( "#navigation> a")[0]はDOM要素を返します。それがhref属性のみを表示するので、それが何を返すかを見るためにalert()を使わないでください。 Chromeでinspect要素を使用するか、firefoxでfirebugを使用してみてください。 –

3

)(.EQ使用し、最初の <a>タグを取得したいですか?
+0

しかし、私は全体のセットを最初のものだけ繰り返す必要はありません。 '$("#navigation> a ")[0];が最初のタグのhref属性を返す理由を知りたいと思います。 – bohan

+1

あなたのお問い合わせ: "私は最初のDOMオブジェクトを取得したいが、最初のオブジェクトの属性は取得しない" – EpokK

関連する問題