Jquery 使用 id 选择器返回一个列表
我在使用以下代码时遇到 jquery 和选择器问题:
<div id="test"></div>
console.log($('#test'));
这总是返回一个类似 [
而不是单个元素。; 的列表。]
这导致每次操作都必须编写 $('#test')[0]
而不是仅 $('#test')
。知道为什么吗?
问候
I'm having trouble with jquery and selectors using the following code:
<div id="test"></div>
console.log($('#test'));
This always returns a list like [<div id="test"></div>]
instead of the single element.
This results on always having to write $('#test')[0]
for every operations instead of only $('#test')
. Any idea on why?
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Jquery 不会返回 HtmlElement,它返回一个 jQuery 对象。
这是一个示例复合设计模式
复合模式描述了一组对象,可以像处理单个对象实例一样处理这些对象。实现此模式允许您以统一的方式处理单个对象和组合。在 jQuery 中,当我们访问单个 DOM 元素或一组 DOM 元素或对其执行操作时,我们可以以统一的方式处理这两者。 http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjquery
Jquery will not return the HtmlElement, it returns a jQuery object.
This is an example of the Composite Design Pattern
The Composite Pattern describes a group of objects that can be treated in the same way a single instance of an object can. Implementing this pattern allows you to treat both individual objects and compositions in a uniform manner. In jQuery, when we're accessing or performing actions on a single DOM element or a group of DOM elements, we can treat both in a uniform manner. http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjquery
jQuery 封装了出于多种原因找到的任何对象。其一,它确保无论如何都不会返回 null。相反,找到的元素被插入到列表中。事实上,即使您正在搜索单个元素,该机制始终保持不变,因此结果将被放入一个元素的数组中,而不是元素本身。
jQuery encapsulates any objects found for a number of reasons. For one, it ensures that no matter what, null will never be returned for example. Rather, the elements found are inserted into a list. The fact that even though you're searching for a single element, the mechanism always remains the same and therefore the results will be placed into an array of one element rather than the element itself.
在 jQuery 中,最好将选择器视为匹配多个项目,如果您使用each 语法来迭代匹配项目,那么您的解决方案将是最好的...
In jQuery it is better to think of selectors as matching multiple items, and your solution would be best if you use the each syntax to iterate through the matches items...
由于 ID 不是唯一的,jQuery 会查找具有该 ID 的每个元素。所以它总是返回一个列表,因为不能保证该元素恰好是一个
As ID is not unique, jQuery looks for every element with such ID. So it's always returns a list, because threre is no guarantee that the element is exactly one