所以我有以下代码来生成一个表并将单击函数应用于表中的每个 td。它还应用从 1 开始的增量 id。当用户单击 td 元素时,我尝试检索 <td>
的 id他们点击了。然而选择器的值为[object Window]。我确信这很简单,但我这里的类似问题都没有帮助,而且我没有看到它。
$("#CMGame").click(function() {
$("#TTTContent").hide();
$("#CMContent").show();
var board = $("#CMBoard");
var htmlString = "";
var count = 0;
for (var i = 0; i < 20; i++) {
htmlString += "<tr>";
for (var i2 = 0; i2 < 20; i2++) {
count++;
htmlString += "<td id='" + toString(count) + "'></td>";
}
htmlString += "</tr>";
}
board.html(htmlString);
$("#CMBoard td").click(function() {
var piece = $(this);
var selector = piece.attr('id');
alert(selector);
/*
if (CMBArray[selector] != 1 OR CMBArray[selector] != 2) {
CMBArray[selector] = 1;
piece.addClass('selected');
}
*/
});
});
最佳答案
您的代码中有 2 个错误,您创建的 td
id 不能只是一个数字,它必须以字母开头,然后您可以删除 toString(count )
并仅使用 count
或将其更改为 count.toString()
,这是正确的方法。
这是规范。对于 DOM id
:
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
这里是toString()
:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
关于javascript - JQuery获取 'id'属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33961407/