代码:
<script>
$(document).ready(function () {
$('#lifegrid tr td').click(function () {
$(this).addClass('selected');
});
$('#animatebutton').click(function () {
$(this).addClass('green');
animate();
});
function animate() {
var cell = [];
for (var x = 0; x < 16; x++) {
cell[y] = [];
for (var y = 0; y < 8; y++) {
if ($('#' + x + ',' + y).hasClass('selected')) {
cell[x,y] = 'alive';
console.log( x + "," + y + " is alive")
} else {
cell[x,y] = 'dead';
console.log( x + "," + y + " is dead")
}
}
}
}
});
</script>
我的代码还包含一个 <table>
与 <td>
元素,所有这些元素都具有“x,y”形式的 id。示例:id="4,12"
.
此代码仅返回“<coordinate>
is dead”,而不管该元素是否已分配到“selected”类。为什么?
最佳答案
在元素“id”值中使用逗号是有问题的,因为逗号是 CSS 选择器元字符。
如果您使用反斜杠转义逗号(或使用逗号以外的其他内容),它应该可以工作。
if ($('#' + x + '\\,' + y).hasClass('selected')) {
请注意,我使用了一个双反斜杠,因为有必要让反斜杠超过字符串常量语法。
关于javascript - .hasClass() 忘记了类分配。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21063578/