使用 JQuery 获取 TD 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3378272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:20:33  来源:igfitidea点击:

To get a value of a TD using JQuery

jquery

提问by user327712

I got a very simple Table with only two rows.
I was thinking what is the best way to get the value from the TD with ID "row2".

我得到了一个只有两行的非常简单的表格。
我在想从 ID 为“row2”的 TD 获取值的最佳方法是什么。

<Table id="testing>
<tr>
<th>
</th>
<td id="row1">hello</td>
</tr>
<tr>
<th>
</th>
<td id="row2">world</td>
</tr>
</table>

Here is my attempt:

这是我的尝试:

$(document).ready(function(){ 
      var r=$("#testing":row2).val();
      alert(r);
});

But I couldn't see any message pop up. What shall I do in the JQuery code if I want to specify the Table ID along with the TD ID?

但是我看不到任何消息弹出。如果我想在指定表 ID 和 TD ID 时在 JQuery 代码中怎么做?

 var r=$("#testing":row2).text();
 var r=$("#testing").children("row2").text();

回答by Pat

This will do it for you:

这将为您做到:

  var r = $("#testing #row2").text();
  alert(r);

In action herefor your viewing pleasure.

在这里为您的观赏乐趣而行动

回答by Sarfraz

Use text()instead of val()

使用text()代替val()

var r = $("#row2").text();

More Info:

更多信息:

回答by Anand

the TD ID is going to be unique be it in any table. It is not right to have two tables with TD ID's same in both tables. Therefore if you feel then append the table id for the TD ID like so: (and then use the answers above)

TD ID 在任何表中都是唯一的。在两个表中使用 TD ID 相同的两个表是不对的。因此,如果您觉得像这样为 TD ID 添加表 ID:(然后使用上面的答案)

 <table id="test1">
    <tr>
    <th>
    </th>
    <td id="test1_row1">hello</td>
    </tr>
    <tr>
    <th>
    </th>
    <td id="test1_row2">world</td>
    </tr>
 </table>

does this help?

这有帮助吗?

回答by Sruthi Mamidala

    <table>
<tr>
    <td class="tdcls">1</td>
    <td class="tdcls">2</td>
    <td class="tdcls">3</td>
</tr>
<tr>
    <td class="tdcls">4</td>
    <td class="tdcls">5</td>
    <td class="tdcls">6</td>
</tr>                   

jquery code to select particular td value

用于选择特定 td 值的 jquery 代码

$(".tdcls").mouseenter(function(){
    var a = $(this).text();
});