2014-01-13 41 views
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 " 

})(); 

它的工作的唯一方法是通过div分配后直接添加alert()声明。我假设这与变量提升有关,但我没有足够的经验知道。

有人可以提供一个可变提升的快速简介以及可能发生的事情吗?谢谢!

+0

你能显示你的*整个*页面吗?你的代码对我来说工作的很好:http://jsfiddle.net/MDRrL/ –

+1

你可以只是谷歌提升,但这里有一个描述:http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html Theren doesn这里似乎没有任何可变的提示,而且代码对我来说工作得很好。 – EmptyArsenal

+0

技术上提升是在这里,但它没有影响这里的任何东西。 –

回答

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 
})(); 

这有可能是你的元素中没有任何元素(也许只是文本节点?)

这里是一个fiddle reproducting the issue。这个是fiddle where it works

+2

谢谢。我确实有孩子的元素,但他们被评论 - 删除评论后,它按预期工作。 – 412