我刚刚读了这篇关于 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/