简体   繁体   English

如何使用Javascript / jQuery获取表格行中的第一个单元格?

[英]How to get first cell in a tablerow with Javascript / jQuery?

Let's say I have a simple table like this one: 假设我有一个像这样的简单表:

<tbody>
<tr>
   <td> A </td>
   <td> B </td>
   <td> C </td>
   <td><input type="button"></td>
</tr>
<tr>
   <td> 1 </td>
   <td> 2 </td>
   <td> 3 </td>
   <td><input type="button"></td>
</tr>

What I'm trying to do is, when I click the button a function takes place which gets the first character in the first table row. 我想做的是,当我单击按钮时,将发生一个函数,该函数在第一个表行中获取第一个字符。 So in row 1 that would be "A", in row 2 that would be "1". 因此,在第1行中将为“ A”,在第2行中将为“ 1”。 None of the rows or cells have unique ID's, so can't use those. 行或单元格都没有唯一的ID,因此不能使用它们。

Right now I was trying to do something like: 现在,我正在尝试执行以下操作:

charValue = $(this).parent()first().text();

But for some reason when I do that I get "ABC" and not just "A". 但是由于某种原因,我得到的是“ ABC”,而不仅仅是“ A”。

Thanks in advance! 提前致谢!

Use find after closest("tr") closest("tr")之后使用find

$(this).closest("tr").find("td").first().text();

Or alternatively td:first 或者td:first

$(this).closest("tr").find("td:first").text();

Simply use this code 只需使用此代码

$("input").click(function() {
  // Bad practice 
  //var charValue = $(this).parent().parent().children().first().text();

  //god practice
  var charValue = $(this).closest("tr").find("td:first").text();

  alert(charValue)
})

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

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