在对象构造函数中创建的HTML按钮onclick事件不起作用

时间:2016-11-04 21:32:56

标签: javascript dom

因此,导致错误的任何内容实际上都必须在此循环中: 通过自己的工作调用gridBox构造函数来创建一个框。但是buildField函数创建的那些不会返回on click事件。

var grid = [];
function buildField(size){
    //loops through each row
    for(var y=0; y<size;y++){
        //loops through each column
        grid[y]=[];
        for(var x=0; x<size; x++){
            //create new object for grid
            grid[y][x] = new gridBox(x,y); 
        }
        document.getElementById("board").innerHTML += "<br>";
    }
}

function gridBox(x,y){
    this.x=x;
    this.y=y;
    var me = this;
    //function to create and add button.
    function makeBtn(){
        var btn = document.createElement("BUTTON");
        btn.type = "BUTTON";
        btn.className = "gridButton";
        btn.value = "BUTTON";
        btn.name = me;
        btn.onclick = function(){
            console.log("click");
        };
        document.getElementById("board").appendChild(btn);
        console.log("madeButton");
    }
    makeBtn();
}

4 个答案:

答案 0 :(得分:0)

document.getElementById("board").innerHTML += "<br>";

这将:

  1. 将DOM转换为HTML
  2. <br>添加到该HTML
  3. 将该HTML转换为DOM
  4. 覆盖现有DOM

    ... onclick事件处理程序不会成为序列化HTML的一部分,因此在第4步发生时它们将丢失。

    再次使用createElementappendChild。请勿使用innerHTML

答案 1 :(得分:-1)

这对我有用:

function gridBox(x,y){
    this.x=x;
    this.y=y;
    var me = this;
    //function to create and add button.
    function makeBtn(){
        var btn = document.createElement("BUTTON");
        btn.className = "gridButton";
        btn.textContent = "Click Me";
        btn.name = me;
        btn.onclick = function(){
            console.log("click");
        };
        document.getElementById("board").appendChild(btn);
        console.log("madeButton");
    }
    makeBtn();
}

gridBox(10,10);
.gridButton {
  height:30px;
  width:100px;
}
<div id=board></div>

答案 2 :(得分:-1)

尝试在文档... appendChild(..)之后添加btn.onClick: 这对我有用

&#13;
&#13;
function gridBox(x,y){
    this.x=x;
    this.y=y;
    var me = this;
    //function to create and add button.
    function makeBtn(){
        var btn = document.createElement("BUTTON");
        btn.type = "BUTTON";
        btn.className = "gridButton";
        btn.value = "BUTTON";
        btn.name = me;
        document.getElementById("board").appendChild(btn);
        btn.onclick = function(){
            console.log("click");
        };
        console.log("madeButton");
    }
    makeBtn();
}
// make simple button
gridBox(10,10);
&#13;
<div id="board">
  
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:-2)

尝试:

btn.addEventListener('click', function(){ });

而不是你的btn.onclick