jQuery get the index of an element in the selection array

Posted in :

在jquery 取得一個集合之後, 如何取得第幾個?

測試直接用 $(query)[index]; 是不行的, 沒有直接錯, 而是接下來去存取這一個object 時, 因為是null, 造成沒有方法或屬性可以存取.

由於我想存取.find() , 顯示錯誤:

下面解法有3, 實測解法1, 還是無法使用, 建議使用解法2.


解法1:

Get an element by index in jQuery
https://stackoverflow.com/questions/9887534/get-an-element-by-index-in-jquery

$(...)[index]      // gives you the DOM element at index
$(...).get(index)  // gives you the DOM element at index
$(...).eq(index)   // gives you the jQuery object of element at index

DOM objects don’t have css function, use the last…

$('ul li').eq(index).css({'background-color':'#343434'});

docs:

.get(index) Returns: Element

.eq(index) Returns: jQuery


解法2:

You can pass the clicked element to the index method:

var $a = $('.container > .item > a').click(function() {
    console.log ( $a.index(this) ); 
});

解法3:

$('a').click(function(){ $("#result").text($('a').toArray().indexOf(this)); });

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *