使用JQuery获取TD的值

时间:2010-07-31 13:23:46

标签: jquery

我有一个非常简单的表,只有两行。
我在想什么是从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>

这是我的尝试:

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

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

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

4 个答案:

答案 0 :(得分:21)

这将为你做到:

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

In action here为了您的观赏乐趣。

答案 1 :(得分:5)

使用text()代替val()

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

更多信息:

答案 2 :(得分:0)

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>

这有帮助吗?

答案 3 :(得分:0)

    <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>                   

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

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