Home > OS >  Why the $('tr td:eq(3)') only affects the first row?
Why the $('tr td:eq(3)') only affects the first row?

Time:02-23

Here is the code:

Try to click on the a4 and b4, it works for a4 but not for b4. Is there any solution to let b4 also has the event listener?

$('tr td:eq(3)').click(function() {
  $(this).text(Math.random());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>a1</td>
    <td>a2</td>
    <td>a3</td>
    <td>a4</td>
  </tr>
  <tr>
    <td>b1</td>
    <td>b2</td>
    <td>b3</td>
    <td>b4</td>
  </tr>
</table>

CodePudding user response:

:eq() is some jquery specifc (deprecated!) selector As per documentation, it only selects one element with index n.

If you want to select every 3rd td in every row, use normal CSS selectors: Note the change from 3 to 4, because nth-child is 0 1 based where eq() seems to be 1 0 based.

$('tr td:nth-child(4)').click(function() {
  $(this).text(Math.random());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>a1</td>
    <td>a2</td>
    <td>a3</td>
    <td>a4</td>
  </tr>
  <tr>
    <td>b1</td>
    <td>b2</td>
    <td>b3</td>
    <td>b4</td>
  </tr>
</table>

CodePudding user response:

use a comma separated list of those you want to target 3 (the 4th one - 'a4'), 7 (the 8th one - 'b4')

$('tr td:eq(3), tr td:eq(7)').click(function(){
  $(this).text(Math.random());
});

Alternatively add a class to the target ones and use that as the selector instead

$('tr td.common-class').click(function(){
  $(this).text(Math.random());
});

CodePudding user response:

Instead of jQuery's deprecated :eq(index) (which does Select the element at index n within the matched set) function, use a fitting selector:

$('td:nth-child(4)').click(function() {
  $(this).text(Math.random());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>a1</td>
    <td>a2</td>
    <td>a3</td>
    <td>a4</td>
  </tr>
  <tr>
    <td>b1</td>
    <td>b2</td>
    <td>b3</td>
    <td>b4</td>
  </tr>
</table>

Even though that works, you really don't need jQuery for that. Here's the vanilla JS DOM API version of it:

for (const cell of document.querySelectorAll('td:nth-child(4)')) {
  cell.addEventListener('click', function() {
    this.textContent = Math.random();
  })
}
<table>
  <tbody>
    <tr>
      <td>a1</td>
      <td>a2</td>
      <td>a3</td>
      <td>a4</td>
    </tr>
    <tr>
      <td>b1</td>
      <td>b2</td>
      <td>b3</td>
      <td>b4</td>
    </tr>
  </tbody>
</table>

  • Related