【问题标题】:Live and Static NodeLists实时和静态节点列表
【发布时间】:2016-08-10 11:02:52
【问题描述】:

好的,所以我在玩静态||实时节点列表,试图测试这个概念,我尝试了不同的场景,但有两个场景引起了我的注意:

var toBeLogged = document.getElementsByTagName('p');
console.log(toBeLogged.length); // Returns 1 to the console
var newEl = document.createElement('p');
document.body.appendChild(newEl);
console.log(toBeLogged.length); // Returns 2 to the console

这是有道理的,因为 getElementsBy... 是一个活动节点集合,因此在更新后再次请求值时,它显然会返回更新后的值。

但是场景二有一个小的变化使得“实时”节点列表充当静态:

var toBeLogged = document.getElementsByTagName('p').length;
console.log(toBeLogged); // Returns 1 to the console
var newEl = document.createElement('p');
document.body.appendChild(newEl);
console.log(toBeLogged); // Returns 1 also to the console

所以我的问题是:为什么为表示活动节点列表的长度属性而创建的变量没有返回活动值,就像直接表示节点列表而不添加属性的变量的值一样。

我试图尽可能准确地描述事物。 提前致谢。感谢您花在这上面的时间。

【问题讨论】:

    标签: javascript dom htmlcollection


    【解决方案1】:

    document.getElementsByTagName('p').length 返回不可变的原始值,不能更改,只能替换。 .length 每次访问时都会返回新的原始值,而 document.getElementsByTagName('p') 每次都返回相同的对象。

    【讨论】:

    • 谢谢,很好的解释。非常感谢 Maxx。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多