Javascript - Onclick 事件应该触发一个函数,但它不起作用

标签 javascript css html

我正在完成类(class)证书的评估。在我的最终任务中,我被要求创建一个迷你 js 游戏,该游戏将在两个镜像面生成随机面孔,其中一侧将缺少面孔。
缺少面孔”上方的 onclick 事件 "应该触发我的函数 nextLevel() ,它将删除两个 div(镜像 div)并生成新内容。
我开发了这个脚本来解决这个问题,但我有 onclick 事件的特定错误。它说:

Uncaught TypeError: Cannot set property 'onclick' of null

但是运行 DOM 查看器时,它显示在左侧 Div 上添加了 5 个子级。请帮助我,我找不到这个问题的解决方案。

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

    function generateFaces(){
      for(i=0;i<numberOfFaces;i++){
        var oImg=document.createElement("img"); // Creates an oimg node
        oImg.setAttribute('src', 'http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png'); // sets the source for img file
        theLeftSide.appendChild(oImg); // append the img to leftSide Div.
        oImg.style.top = Math.floor(Math.random()*401)+'px';
        oImg.style.left = Math.floor(Math.random()*401)+'px';
     }
     copyDiv();
    }
    function copyDiv(){
      var cloned = theLeftSide.cloneNode(true);
      cloned.removeChild( cloned.childNodes[ cloned.childNodes.length - 1 ] );
      theRightSide.appendChild(cloned);
    }
    theLeftSide.lastChild.onclick=function nextLevel(event){
    event.stopPropagation();
    numberOfFaces += 5;
    deleteAllChilds();
    generateFaces();
  }; 

  /*
    theBody.onclick =function gameOver() {
      alert("Game Over!");
      theBody.onclick = null;
      theLeftSide.lastChild.onclick = null;
    };
    */
    function deleteAllChilds(){
      while(theLeftSide.childNodes.length>0){
        theLeftSide.removeChild(theLeftSide.childNodes[theLeftSide.childNodes.lenth-1]);
      }
      while(theRightSide.childNodes.length>0){
        theRightSide.removeChild(theRightSide.childNodes[theRightSide.childNodes.lenth-1]);
      }
    }

最佳答案

这是函数nextLevel的位置。将其添加到函数generateFaces中将提供我一直在寻找的可用性。谢谢大家。

关于Javascript - Onclick 事件应该触发一个函数,但它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36683158/

相关文章:

javascript - OnPress 不适用于 react native map 中的标记

javascript - 在 Gridster 上,拖动期间将小部件保持在鼠标下方

css - float 的 div 仍然在垂直线上,而不是它们应该水平的

jquery - Div默认继承parents属性吗

javascript - 在饼图的图例中添加系列值

javascript - PDF.js 使用滚动条渲染 pdf

javascript - 如何在 JavaScript 中将 1e-8 转换为 0.00000001

带有图标的jquery向左滑动菜单

jquery - 使用 jquery 滑动导航栏

html - ZEN CODING - 引用 parent id 分配 Id