简体   繁体   English

如何使用jQuery在表格行下分别选择各个表格数据的文本

[英]How to select the text of respective table data separately under table row with jQuery

This is the code 这是代码

<tbody id="table-body">

 <tr>
      <td id="c1">AAA0</td>
      <td id="c2">2%</td>

 </tr>

</tbody>

I want to select data of ID c1 under < tr > tag. 我想在<tr>标签下选择ID c1的数据。 I am using this jQuery code but it is selecting whole text under < tr > tag. 我正在使用此jQuery代码,但它正在<tr>标记下选择整个文本。

$("#table-body").on('click','tr',function(e){
e.preventDefault();
console.log($(this).text());
})

I am getting AAA02% as the output if this code. 如果此代码,我将获得AAA02%作为输出。 I want to select AAA0 and 2 separately. 我想分别选择AAA02 How to do it ? 怎么做 ?

Since there is more than one td element in each clicked tr element, you have to loop through each of them to get the text individually. 由于每个单击的tr元素中都有多个td元素,因此您必须循环浏览每个td元素以分别获取文本。

You can use find() and each() like the following way: 您可以像以下方式使用find()each()

 $("#table-body").on('click','tr',function(e){ $(this).find('td').each(function(){ console.log($(this).text()); }) }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody id="table-body"> <tr> <td id="c1">AAA0</td> <td id="c2">2%</td> </tr> </tbody> </table> 

Try this: 尝试这个:

console.log($(this).find('.c1').text());

And use class attribute instead of id 并使用class属性代替id

You are getting all text inside tr because you are binding click event on the tr and so $(this) refers to the tr you clicked. 你得到的所有文字里面tr ,因为你要绑定click该事件tr$(this)是指tr你点击。

To get AAA0 only, you can use children() and pass id to select a specific td 要仅获取AAA0 ,可以使用children()并传递id以选择特定的td

$("#table-body").on('click','tr',function(e){
    console.log($(this).children('#c1').text());
});

But since you are assinginig id to the td 's, you can also directly attach the click event to the td as 但是由于您将id关联到td ,因此您还可以将click事件直接附加到td

$("#table-body #c1").on('click','tr',function(e){
  console.log($(this).text());
});

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

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