【问题标题】:How to overcome this onclick event failure in JS?如何克服 JS 中的这个 onclick 事件失败?
【发布时间】:2015-12-23 15:23:42
【问题描述】:

我正在制作一个简单的游戏。屏幕一分为二,两边都生成笑脸。然而,左侧包含一张笑脸。单击它后,您应该进入下一个级别,每侧都有 5 个笑脸。目标是每次都在左侧找到奇怪的笑脸。

不过我有这个问题:Uncaught TypeError: Cannot set property 'onclick' of null

似乎与这一行有关:theLeftSide.lastChild.onclick = function nextLevel(event){

有什么问题?这是我剩下的 JS 部分代码。

var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
var theBody = document.getElementsByTagName("body")[0];

function generateFaces(){
    var i = 0;
    while(i < numberOfFaces){
        var top = Math.random() * 400;
        top = Math.floor(top);
        var left = Math.random() * 400;
        left = Math.floor(left);

        var face = document.createElement("img");
        face.setAttribute("src", "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png");
        face.style.top = top + "px";
        face.style.left = left + "px";

        theLeftSide.appendChild(face);
        i++;
    }
    leftSideImages = theLeftSide.cloneNode(true);
    leftSideImages.removeChild(leftSideImages.lastChild);
    theRightSide.appendChild(leftSideImages);
};

theLeftSide.lastChild.onclick = function nextLevel(event){
    event.stopPropagation();
    while (theLeftSide.firstChild){
        theLeftSide.removeChild(theLeftSide.firstChild);
    }
    while (theRightSide.firstChild){
        theRightSide.removeChild(theRightSide.firstChild);
    }
    numberOfFaces += 5;
    generateFaces();
};
    theBody.onclick = function gameOver(){
        alert("Game Over!");
        theBody.onclick = null;
        theLeftSide.lastChild.onclick = null;
    };

非常感谢您的帮助。谢谢。

【问题讨论】:

  • 这意味着 lastChild 为空...
  • 看起来 generateFaces() 是将子节点添加到“theLeftSide”的原因。因此,在单击它之前没有 lastChild 可用。尝试在点击事件之外添加 generateFaces() 以首先用至少一个孩子填充侧面。

标签: javascript


【解决方案1】:

如果 DOM 元素没有子元素,则最后一个子元素返回 null。检查以确保“#leftSide”DOM 元素有一个子元素。

来自Mozilla Developer Network

Node.lastChild 只读属性返回节点的最后一个子节点。如果其父节点是元素,则子节点通常是元素节点、文本节点或注释节点。如果没有子元素,则返回 null。

【讨论】:

  • 谢谢 Hunterc 和 @Kyle!我已将 theLeftSide.lastchild.onclick 和 theBody.onclick 部分放入函数 generateFaces() 中,现在它可以完美运行了! :) 现在我知道另一件事了,太好了,谢谢! :)
猜你喜欢
  • 2014-08-04
  • 2013-09-15
  • 2015-08-25
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多