且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery .each()返回DOM元素而不是一个jQuery对象

更新时间:2023-11-03 09:59:10

该文档没有错,但是您可能会误会jQuery对象是什么。



jQuery对象由 $ ()函数。所以 $(span [id $ ='_ TotalItemCost'])是一个jQuery对象,其中包含选择的每个span元素。



使用 .each()将遍历jQuery对象中包含的元素。这就是为什么这是一个DOM节点,而不是一个jQuery对象。



你使用 $(this)在此特定元素上使用jQuery方法。


I could be misunderstanding what is happening but from what I can tell I am getting a DOM element and not a jQuery object when I use .each().

The below will not work as this refers to a DOM element and not a jQuery object

$("span[id$='_TotalItemCost']").each(function() {
    var someText = this.text();
});

Modified to transform this to a jQuery object and all is well

$("span[id$='_TotalItemCost']").each(function() {
    var someText = $(this).text();
});

Is there something funky with my selector? Is the jQuery .each() documentation wrong and it's not a jQuery object but rather a DOM element returned by .each()?

The documention is not wrong but you may misunderstand what a jQuery object is.

The jQuery object is returned by the $() function. So $("span[id$='_TotalItemCost']") is one jQuery object which contains every span element selected.

Using .each() will iterate over the elements contained in the jQuery object. This is why this is a DOM node and not a jQuery object.

You did the right thing by using $(this) to use the jQuery methods on this specific element.