[英]Table cell event listener
I have a while stuck with this code and don't know what's wrong!我有一段时间被这段代码困住了,不知道出了什么问题! this jQuery code function is for a single web page application of a Game.
此 jQuery 代码功能用于游戏的单个网页应用程序。 I need to change a table cell
background-color
by clicking on it but it doesn't work:我需要通过单击来更改表格单元格的
background-color
,但它不起作用:
$("document").ready(function() {
var y, x, cellColor;
//console.log("tata");
$("#sizePicker").submit(function(event) {
event.preventDefault();
});
$('input[type="submit"]').click(function makeGrid(y, x) {
y = Number($("#inputHeight").val());
x = Number($("#inputWeight").val());
$("#pixelCanvas tr").remove();
for (i = 0; i < y; i++) {
$("#pixelCanvas").append("<tr class='vertical'></tr>");
}
for (j = 0; j < x; j++) {
$(".vertical").append("<td class='cell' ></td>");
}
$("#pixelCanvas tr td").css("background-color", "red");
});
$("#pixelCanvas tr td").click(function() {
$(this).css("background-color", "blue");
});
});
I think the problem is that when you bind a click event to the table cells, those cells are not created yet.我认为问题在于当您将单击事件绑定到表格单元格时,尚未创建这些单元格。 Try binding a click event to the body and use the
"#pixelCanvas tr td"
selector to filter event consumers: instead of $("#pixelCanvas tr td").click
write the following:尝试将点击事件绑定到正文并使用
"#pixelCanvas tr td"
选择器来过滤事件使用者:而不是$("#pixelCanvas tr td").click
编写以下内容:
$("body").on("click", "#pixelCanvas tr td", function() {
$(this).css("background-color", "blue");
});
The problem is that the elements have not been created until the click of 'input[type="submit"]' is done.问题是元素在点击“input[type="submit"]”之前没有被创建。 Move the binding of the click of the cells into the click handler of 'input[type="submit"]':
将单元格点击的绑定移动到'input[type="submit"]'的点击处理程序中:
$("document").ready(function() {
var y, x, cellColor;
//console.log("tata");
$("#sizePicker").submit(function(event) {
event.preventDefault();
});
$('input[type="submit"]').click(function makeGrid(y, x) {
y = Number($("#inputHeight").val());
x = Number($("#inputWeight").val());
$("#pixelCanvas tr").remove();
for (i = 0; i < y; i++) {
$("#pixelCanvas").append("<tr class='vertical'></tr>");
}
for (j = 0; j < x; j++) {
$(".vertical").append("<td class='cell' ></td>");
}
$("#pixelCanvas tr td").css("background-color", "red");
$("#pixelCanvas tr td").click(function() {
$(this).css("background-color", "blue");
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.