document.element中的空引用错误

时间:2016-06-18 05:28:29

标签: javascript html css

我在append child面临错误,因为对象null值错误实际上我已经使用document get元素在脚本顶部创建了对象 而我正试图让问题得到解决,因为左侧是div在那里需要一些帮助试图找出它。请你阅读

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Game</title>
<style>

imgg{
    position: absolute;

}

div{
    width: 500px;
    height: 500px;
    position: absolute;
}

#rightSide { left: 500px;
    border-left: 1px solid black }

</style>
<script>

    var numberOfFaces =5 ;
    var theLeftSide = document.getElementById("leftSide");

    function generateFaces(){

        for(var i = 1 ; i <= numberOfFaces ; i++)
        {
            var imgg = document.createElement("img");
            imgg.src = "smile.png";
            imgg.style.height = "100px";
            imgg.style.width = "100px";
            imgg.style.top = Math.random() *400 ;
            imgg.style.left = Math.random() *400 ;
            theLeftSide.appendChild(imgg);
        }
    }

</script>

</head>
<body onload="generateFaces()">
<h2>Matching Game</h2>
<p>Click on the extra smiling face on the left.</p>

<div id="leftSide"></div>
<div id="rightSide"></div>


</body>
</html>

2 个答案:

答案 0 :(得分:0)

  • <script>作为last-child的{​​{1}}放置为使用<body>访问元素时,元素不在DOM-api
  • DOM设为position
  • 在分配absolutepx(pixel)
  • 时将单位添加为top

left
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");

function generateFaces() {

  for (var i = 1; i <= numberOfFaces; i++) {
    var imgg = document.createElement("img");
    imgg.src = "http://i185.photobucket.com/albums/x304/metalife/transmetropolitan-smile.png";
    imgg.style.height = "100px";
    imgg.style.width = "100px";
    imgg.style.position = 'absolute';
    imgg.style.top = Math.random() * 400 + 'px';
    imgg.style.left = Math.random() * 400 + 'px';
    theLeftSide.appendChild(imgg);
  }
}
imgg {
  position: absolute;
}
div {
  width: 500px;
  height: 500px;
  position: absolute;
}
#rightSide {
  left: 500px;
  border-left: 1px solid black
}

答案 1 :(得分:0)

document.getElementById("leftSide");如果将脚本放在head内,则会出错。原因是当js尝试解析这一行但没有这样的DOM时。

您可以使用

解决此问题
  1. window.onload
  2. 在关闭正文标记

    之前放置脚本标记
    <body>
        // Dom
    <script>
          // Rest of code
    </script>
    </body>
    
  3. 使用window.onload

    <head>
      //Rest of code
    
    <script>
       window.onload = function(){
       var numberOfFaces =5 ;
        var theLeftSide = document.getElementById("leftSide");
          function generateFaces(){
           for(var i = 1 ; i <= numberOfFaces ; i++)
            {
                var imgg = document.createElement("img");
                imgg.src = "smile.png";
                imgg.style.height = "100px";
                imgg.style.width = "100px";
                imgg.style.top = Math.random() *400 ;
                imgg.style.left = Math.random() *400 ;
                theLeftSide.appendChild(imgg);
            }
        }
    
    }
    </script>
    </head>
    

    检查此JSFIDDLE,脚本包含在正文中