gpt4 book ai didi

javascript - Jquery 使用 id 选择器返回一个列表

转载 作者:搜寻专家 更新时间:2023-11-01 04:11:28 24 4
gpt4 key购买 nike

我在使用以下代码时遇到了 jquery 和选择器的问题:

<div id="test"></div>
console.log($('#test'));

这总是返回一个类似 [<div id=​"test">​</div>​] 的列表而不是单个元素。

这导致总是不得不写 $('#test')[0]对于每个操作,而不仅仅是 $('#test') .知道为什么吗?

问候

最佳答案

Jquery 不会返回 HtmlElement,它返回一个 jQuery 对象。

A jQuery object contains a collection of Document Object Model (DOM) elements that have been created from an HTML string or selected from a document. Since jQuery methods often use CSS selectors to match elements from a document, the set of elements in a jQuery object is often called a set of "matched elements" or "selected elements"

The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join(). http://api.jquery.com/Types/#jQuery

这是复合设计模式的一个例子

复合模式描述了一组对象,这些对象可以像处理单个对象实例的方式一样处理。实现此模式允许您以统一的方式处理单个对象和组合。在 jQuery 中,当我们在单个 DOM 元素或一组 DOM 元素上访问或执行操作时,我们可以以统一的方式对待两者。 http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjquery

关于javascript - Jquery 使用 id 选择器返回一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5140919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com