javascript - 'live'元素的解释

标签 javascript live getelementsbytagname nodelist selectors-api

我刚刚读了这篇关于 NodeLists 的文章:

http://www.nczonline.net/blog/2010/09/28/why-is-getelementsbytagname-faster-that-queryselectorall/

如果我理解正确的话, getElementsByTag 名称是实时的,而 querySelectorAll 不是。 那么有人可以向我解释一下为什么 pNotLive 的标题是“stackoverflow”吗? :

var pLive = document.getElementsByTagName( 'p' )[3];
var pNotLive = document.querySelectorAll( 'p' )[3];

pLive.title = "stackoverflow"
console.log( pNotLive.title ); // stackoverflow

//you can run this snippet in your console to verify

最佳答案

正如您的链接所解释的,getElementsByTagName 方法返回一个集合,该集合会在 DOM 更改时自动更新。因此,如果您调用该方法,然后将一个新元素添加到 DOM,您的集合将自动使用新元素进行更新。

如果您使用 querySelectorAll,您将获得一个 DOM 元素的静态列表,该列表不会自动更新。

我相信您在示例中使用的行为的原因是因为列表是静态的,而不是元素本身。因此,静态方法仅意味着列表不会更改,因此添加/删除元素不会更改您的列表。但是,当您调用 title 属性时,您的列表只是指向该元素,并且该元素与您创建列表时的元素不同。

简而言之,它更多的是一个引用列表(对 DOM 节点),而不是一个数据对象列表(具有固定数据)。

关于javascript - 'live'元素的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16280914/

相关文章:

javascript - 当手机锁 native react 时 Socket.io 失去连接

jQuery:取消绑定(bind)与 live() 绑定(bind)的事件

Jquery 注册点击未点击的元素的奇怪行为

Java getElmentsByTagName 与通配符

javascript - 为什么我的网站中的脚本会出现此错误?

javascript - 传递给createMediaElementSource的HTMLMediaElement具有跨源资源,节点将输出静音

javascript - Android 标记的图标

email - 如何修复 "421 RP-001 The mail server IP connecting to Windows Live Hotmail server has exceeded the rate limit"问题?

java - 使用 JAVA 将标签从 xml 文件导入到另一个文件

javascript - 在这种情况下如何调用输入?