简体   繁体   中英

Select a child td of a tr by id in a table

I have a table from which, through jQuery, I want to select the text of firstname from the tr whose button was pressed.

A tr row look like :

....
<tr id = "2">
    <td>
        <input type="checkbox">
    </td>
    <td id = "firstname">
        John
    </td>
    <td id = "lastname">
         Doe
    </td>
    <td>
            <button id = "2" class="button">change</button>
    </td>
</tr>
....

That button above is linked to a jQuery :

$(".button").click(function(){
    var element = $(this);
    var id = element.attr("id");
    var newusername = $("tr#"+id+" > td#firstname").html();
    alert(newusername);
});

Why doesn't my selector work?

Since IDs must be unique, try ...

<tr id = "2">
  <td>
    <input type="checkbox">
  </td>
  <td class = "firstname">
    John
  </td>
  <td class = "lastname">
     Doe
  </td>
  <td>
     <button data-id = "2" class="button">change</button>
  </td>
</tr>

... and ...

$(".button").click(function(){
  var element = $(this);
  var id = element.data("id");
  var newusername = $("#" + id + " > .firstname").html();
  alert(newusername);
});

Changing the name IDs to classes and changing the selection should work. Also, only one ID of 2. I used data-id on the button so that I can still select what the value is and didn't duplicate the id .

NOTE:

The data- "data dash" attribute is an attribute that I used here to allow for quicker capture of the attribute; jQuery has a .data() function that specifically looks for these types of attributes.

.data() link

It seems that you have several element with the same id. In that case, the correct usage is to use a class:

<td class="firstname">
...
<td class = "lastname">

Then your selector becomes: $("tr#"+id+" > td.firstname")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM