在addEventListener方法之外调用函数

时间:2019-04-25 20:55:39

标签: javascript typescript

我有一个创建10x10表的JavaScript代码,当我单击一个单元格时,addEventListener方法将打印x,y坐标并执行如下函数:

create_grid(name){
  var dim = 10;
  var my_field = document.createElement("table");

  for (var i = 0; i < dim; i++) {
    var row = document.createElement("tr");
    for (var j = 0; j < dim; j++) {
      var td = document.createElement("td");
      td.setAttribute("id", i + "," + j);

      td.addEventListener("click", function () {
        var obj = {
          x: this.id.split(",")[0],
          y: this.id.split(",")[1]
        };

        console.log("cell pressed: " + obj.x + "  " + obj.y);
      });
      row.appendChild(td);
    }
    my_field.appendChild(row);
  }
  document.getElementById(name).appendChild(my_field);
}

我还有另一个功能,例如:

myFunction(x,y){

    // do something
}

我想在create_grid函数的addEventListener内部调用myFunction:

td.addEventListener("click", function () {
        var obj = {
          x: this.id.split(",")[0],
          y: this.id.split(",")[1]
        };

        console.log("cell pressed: " + obj.x + "  " + obj.y);


        myFunction(obj.x, obj.y); // THIS DOESN'T WORK!
});

打字稿文件的结构如下:

export class gameComponent {

      create_grid(name){
          // code
      }

      myFunction(x,y){
         // code 
      }

}

1 个答案:

答案 0 :(得分:0)

尝试

function myFunction(x,y){
  console.log(x+'-'+y);
}

function create_grid(name){
  var dim = 10, s='';
  
  for(let i=0; i<dim; i++) {
    s+='<tr>'
    for(let j=0; j<dim; j++) s+=`<td onclick="myFunction(${[i,j]})">x</td>`;
    s+='</tr>'
  }

  this[name].innerHTML= '<table>' + s + '</table>';
}

create_grid('xxx');
td {cursor: pointer}
Click on 'x':
<div id='xxx'></div>