3

I tried to update data attribute as my work below.

When I click square,data attribute should be incremented.

But the result is a little bit different. It seems not to be incremented.

How can I fix them?

And Why this issue inccured?

Thanks

$("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>
Heisenberg
  • 4,787
  • 9
  • 47
  • 76
  • 1
    because you data layer is always 0 and when you click the button it always starts from 1 and you are attaching your event listener to the first td only not to the previous one as you are expecting which would give you a sequence – EugenSunic Apr 22 '20 at 12:31
  • there's a semicolon missing at `index+=1` – m1ck Apr 22 '20 at 12:33
  • `data()` is not just a getter for `data-` attributes. See [jQuery .data() does not work, but .attr() does](https://stackoverflow.com/q/8707226/215552) – Heretic Monkey Apr 22 '20 at 12:42

2 Answers2

3

An Html element can have a dataset and/or an attribute.

In your code you get the value of the dataset and change like if it is an attribute. This is your mistake.

For more details see .data() and .attr().

If you are inrested in attribues you need to use:

$("td").click(function() {
    index=$(this).attr('data-layer');
    index = index + 1;
    $(this).attr('data-layer',index);
    console.log(this);
});

Instead, if you need to use 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>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
1

$("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>
Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26