我尝试在下面的工作中更新data属性。
当我点击正方形时,data属性应该是incremented。
但结果有点不同。它似乎没有递增。
我该如何修复它们呢?
为什么会引发这个问题呢?
谢谢
$("td").click(function() {
index=$(this).data('layer');
index+=1
$(this).attr('data-layer',index);
console.log(this);
});td {
border:solid black 1px;
width:50px;
height:50px;
cursor:pointer;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td data-layer="0"></td>
</tr>
</table>
发布于 2020-04-22 20:48:49
超文本标记语言元素可以有dataset和/或attribute。
在您的代码中,您将获取数据集的值并进行更改,就像它是一个属性一样。这是你的错误。
如果你沉浸在属性中,你需要使用:
$("td").click(function() {
index=$(this).attr('data-layer');
index = index + 1;
$(this).attr('data-layer',index);
console.log(this);
});相反,如果您需要使用dataset:
$("td").click(function() {
index=$(this).data('layer');
index = index + 1;
$(this).data('layer',index);
console.log($(this).data('layer'));
});td {
border:solid black 1px;
width:50px;
height:50px;
cursor:pointer;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td data-layer="0"></td>
</tr>
</table>
发布于 2020-04-22 20:33:51
$("td").click(function() {
const index = $(this).attr('data-layer');
const newIndex = Number(index) + 1;
$(this).attr('data-layer', newIndex);
console.log(this);
});td {
border:solid black 1px;
width:50px;
height:50px;
cursor:pointer;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td data-layer="0"></td>
</tr>
</table>
https://stackoverflow.com/questions/61365094
复制相似问题