javascript - 如何在javascript中增加数据索引

标签 javascript html jquery css

我尝试更新 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/

相关文章:

javascript - 使用 jQuery 更改 CSS 类

jquery - 使用 Tempus Dominus 中的 viewDate 函数设置日历值

javascript - 缩放时保持建议框 div 相对于输入

JavaScript : How to get a name of an element index?

javascript - PIXI : Change only non transparent pixels of sprite to one solid color

java - 使用deployJava.js在javascript中调用java方法

javascript - 在输入字段发生任何变化时调用 jQuery 函数

javascript - 如何在 Vue 自定义指令中添加事件监听器?

javascript - jQuery AddClass 然后删除一个类

javascript - 复制 URL 参数并粘贴到 HTML 上