在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
- Description: Retrieve the DOM elements matched by the jQuery object.
- See: https://api.jquery.com/get/
.eq(index)
Returns: jQuery
- Description: Reduce the set of matched elements to the one at the specified index.
- See: https://api.jquery.com/eq/
解法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)); });