2

考虑这个 JS(它在结束时运行body并导致错误)

(function(){
    "use strict";

    var div = document.getElementById("hook"),
        ul = div.firstElementChild,
        last_li = ul.lastElementChild;

    alert(div) // alerts "Uncaught TypeError: Cannot read property 'children' of undefined"  

})();

然后我删除了逗号并添加了var关键字,但收到了类似的错误(它不是 HTML):

(function(){
    "use strict";

    var div = document.getElementById("hook");
    var ul = div.firstElementChild;
    var last_li = ul.lastElementChild;

    alert(div) // alerts "Uncaught TypeError: Cannot read property 'lastElementChild' of undefined " 

})();

它起作用的唯一方法是alert()在赋值之后直接添加语句div。我假设这与变量提升有关,但经验不足,无法确定。

有人可以简要介绍一下变量提升以及这里可能发生的情况吗?谢谢!

4

1 回答 1

3

这不是吊装。

这里发生的情况如下:

(function(){
    "use strict";

    // this returns an element otherwise the next line would not work
    // that means the element is found in the DOM
    var div = document.getElementById("hook"), 
        // this returns the value `undefined` or `null` 
        ul = div.firstElementChild,
        // this is a TypeError, since `ul` is undefined
        last_li = ul.lastElementChild;

    alert(div) // we never actually get to this line
})();

您拥有的元素可能没有元素(可能只是文本节点?)

这是重现问题的小提琴

这是一个可行的小提琴

于 2014-01-13T17:47:49.977 回答