jQuery选择器返回什么样的对象

What kind of object does a jQuery selector return?

本文关键字:对象 什么样 返回 选择器 jQuery      更新时间:2023-09-26

我正在尝试获取"li"元素的html,并将其作为字符串进行提醒。

HTML:

<ul>
    <li>lorem ipsum dolor <span>sit</span> amet 1</li>
    <li>lorem ipsum dolor <span>sit</span> amet 2</li>
    <li>lorem ipsum dolor <span>sit</span> amet 3</li>
    <li>lorem ipsum dolor <span>sit</span> amet 4</li>
    <li>lorem ipsum dolor <span>sit</span> amet 5</li>
    <li>lorem ipsum dolor <span>sit</span> amet 6</li>
</ul>
<p id="greeting">Hello <strong>World</strong>!</p>

Javascript:

$(document).ready(function(e){
    var list =  $("li");
    var greeting = $("#greeting");
    var content ="";
    for(var i=0, len = list.length; i<len; i++) {
        content += $(list[i]).html();   
        //why do I have to use the $ here instead of just doing list[i].html()
      //content += list[i].html(); why does this not work?
    }
    alert(content);
    alert(greeting.html());  //why does this work without the $ ?
});

我已经做了一些研究,并了解到jQuery选择器返回封装在jQuery对象中的DOM元素,这样我们就可以对其应用jQuery方法,但为什么没有$,行greeting.html()就可以正常工作呢?

TypeError:list[i].html不是函数

为什么在执行list[I].html而不是$(list[I]).html()时会出现此错误?

这是小提琴。

jQuery选择返回一个jQuery选择集(一个"jQuery对象")。该对象也是一个"类似数组"的对象,这意味着您可以像示例中那样通过索引器表示法访问所选内容。

选择集中的元素dom元素

var jQ = $("div"); // get all divs
jQ[0]; // the first div, a DOMElement
$(jQ[0]); // a selection containing the first div of the old selection
jQ.eq(0); // convenience for the above. 

API这样做的原因是为了效率,如果选择10000个div,那么创建10000个新对象是浪费的。

它们存储为HTMLElement的数组,封装为单个jQuery对象。

如果你想得到一个元素,你可以使用.eq():

content += list.eq(i).html();  

记录$("li"),您就会明白。

它是jQuery对象中DOM元素的集合,当您使用$("li")[i]时,它会返回存储在jQuery对象内的DOM Elment,您可以在家中使用list[i].inerHTML来获取html,而无需转换回jQuery对象,就像使用普通Javascript选择的元素一样。