I have a JavaScript code that creates a 10x10 table, and when I click on a cell an addEventListener method prints the x,y cordinates and execute a function like below:
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);
}
I have another function like:
myFunction(x,y){
// do something
}
I would like to call myFunction inside the addEventListener of create_grid function:
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!
});
The structure of the typescript file il this:
export class gameComponent {
create_grid(name){
// code
}
myFunction(x,y){
// code
}
}
Try
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.