如何使用selector返回jQuery对象的数组 [英] How to return array of jQuery object with selector
问题描述
我正在尝试从选择器中检索jquery对象的数组,因此我不必再次重新查询它们以便稍后进行修改。
I am trying to retrieve an array of jquery object from selector, so I would not have to re-query them again for modification later.
但是,当我使用代码进行测试时,我发现如果jquery选择器不查询特定元素,那么jquery选择器会将数组作为html元素返回。
But, while I testing with the code, I find that the jquery selector returns array as html element if it does not query specific element.
//HTML
<div id='nav'>
<div class='menu'>menu 1</div>
<div class='menu'>menu 2</div>
<div class='menu'>menu 3</div>
<div class='menu'>menu 4</div>
<div class='menu'>menu 5</div>
</div>
//JS
//this works
$('#nav .menu:eq(0)').html('haha');
//this does not
$('#nav .menu').get(0).html('halo w');
-> Uncaught TypeError: Object #<HTMLDivElement> has no method 'html'
我的问题是为什么它返回html元素而不是jquery object.How我可以从选择器中检索jquery对象的数组。
My question is why does it return html element and not jquery object.How can I retrieve an array of jquery objects from selector.
这是JSFiddle示例。
Here's the JSFiddle example.
http://jsfiddle.net/mochatony/K5fJu/7/
推荐答案
.get(i)
返回DOM元素。你想要的是其中之一:
.get(i)
returns the DOM element. What you want is one of these:
$('#nav .menu').first()
$('#nav .menu').eq(0)
参见 http://api.jquery.com/category/traversing/filtering/ 获取可能的过滤功能列表。
See http://api.jquery.com/category/traversing/filtering/ for a list of possible filter functions.
这篇关于如何使用selector返回jQuery对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!