【问题标题】:How to increment data index in javascript如何在javascript中增加数据索引
【发布时间】:2020-04-22 12:27:08
【问题描述】:

我尝试在下面更新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>

【问题讨论】:

  • 因为您的数据层始终为 0,并且当您单击按钮时,它始终从 1 开始,并且您将事件侦听器附加到第一个 td,而不是像您期望的那样附加到前一个你是一个序列
  • index+=1 处缺少分号
  • data() 不仅仅是data- 属性的getter。见jQuery .data() does not work, but .attr() does

标签: javascript html jquery css


【解决方案1】:

一个 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>

【讨论】:

    【解决方案2】:

    $("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>

    【讨论】:

    • @dgknca 这是一个字符串
    • @dgknca 自己试试看是不是数字
    • 用typeof index可以看到
    猜你喜欢
    • 2020-06-29
    • 1970-01-01
    • 2015-12-18
    • 2020-11-16
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多