简体   繁体   English

在表中按ID选择tr的子td

[英]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. 我有一个表,通过该表,我想通过jQuery从按下按钮的tr中选择名字文本。

A tr row look like : tr行看起来像:

....
<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 : 上面的按钮链接到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 ... 由于ID必须是唯一的,请尝试...

<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. 将名称ID更改为类并更改选择应该起作用。 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 . 另外,只有一个ID2。我在按钮上使用了data-id ,因此我仍然可以选择值是什么,并且不重复id

NOTE: 注意:

The data- "data dash" attribute is an attribute that I used here to allow for quicker capture of the attribute; data- “数据破折号”属性是我在此处使用的属性,用于更快地捕获该属性。 jQuery has a .data() function that specifically looks for these types of attributes. jQuery有一个.data()函数,专门用于查找这些类型的属性。

.data() link 。数据链接

It seems that you have several element with the same id. 看来您有几个具有相同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") 然后,您的选择器将变为: $("tr#"+id+" > td.firstname")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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