我尝试更新 data
属性,如下我的工作。
当我点击方 block 时,data
属性应该递增
。
但是结果有点不同。好像没有增加。
我该如何修复它们?
为什么会出现这个问题?
谢谢
$("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>
最佳答案
Html 元素可以有 dataset和/或attribute .
在代码中,您可以获得数据集的值并进行更改,就像它是属性一样。这是你的错误。
有关更多详细信息,请参阅 .data()和 .attr() .
如果您对需要使用的属性感兴趣:
$("td").click(function() {
index=$(this).attr('data-layer');
index = index + 1;
$(this).attr('data-layer',index);
console.log(this);
});
相反,如果您需要使用数据集:
$("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>
关于javascript - 如何在javascript中增加数据索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61365094/