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

标签 javascript jquery html innerhtml

<分区>

我正在尝试获取“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() 时会出现此错误?

这是 fiddle .

最佳答案

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

选择集中的元素dom元素,而不是jQuery选择集本身。如果您想将 DOM 元素转换为 jQuery 选择集,您需要将其包装在 $(yourElement) 中。

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 个新对象是浪费的。

关于javascript - jQuery 选择器返回什么样的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33390659/

相关文章:

javascript - 动态水平滚动

javascript - image.onError 事件永远不会触发,但图像不是有效数据 - 需要解决方法

javascript - 如何只显示select标签中的某些选项?

php - jQuery AJAX - 设置 PHP session 变量

javascript - 如何根据 sibling 之间的排序元素查找索引。?

php - 将 HTML 表单值存储到 PHP 中的数组中并打印

JavaScript 时间量

javascript - 将背景图像添加到 WebGL 3D 场景

javascript - 类确实存在但未找到

javascript - 通过垂直进入制作 Div 容器负载