简体   繁体   English

jQuery-.first()与[0]元素

[英]jQuery - .first() versus [0] element

Using jQuery 3.1.1, why are the results of these two different? 使用jQuery 3.1.1,这两个的结果为何不同?

$('dd[data-something]').first().innerText;

^ returns undefined ^返回未定义

$('dd[data-something]')[0].innerText;

^ returns valid data ^返回有效数据

Wouldn't the 0th element of an array also be the .first() element? 数组的第0个元素也不是.first()元素吗?

Edit : Thanks all, I got it, jQuery object versus DOM element. 编辑 :谢谢,我明白了,jQuery对象与DOM元素。 As the debugger clearly showed before I could delete this :) That's a clear sign its time to call it quits for the day. 正如调试器在删除该命令之前已明确显示的那样:)这是一个明确的信号,它可以立即退出。

因为first返回一个jQuery对象,该对象围绕该集合中的第一个原始DOM元素包装(它没有innerText属性,但确实具有该便捷的text方法),并且[0]直接访问该原始DOM元素(该对象确实具有一个innerText属性)大多数浏览器)。

first() will return a jQuery object which is different from the normal JavaScript object and won't work with native JavaScript APIs, here's a qoute from the official documentation first()将返回一个与普通JavaScript对象不同的jQuery对象,并且无法与本机JavaScript API一起使用,这是官方文档中的qoute

the .first() method constructs a new jQuery object from the first element in that set. .first()方法从该集合中的第一个元素构造一个新的jQuery对象。

The second one (index zero) will return a JavaScript object it's almost like calling the element using querySelectorAll() 第二个(索引为零)将返回一个JavaScript对象,就像使用querySelectorAll()调用元素一样

So if you want to get the text use text() from jQuery and it will work 因此,如果要获取文本,请使用jQuery中的text() ,它将起作用

$('dd[data-something]').first().text('new text'); // this will change the text

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM