从表中的其他td获取其他值

getting the other values from other td in a table

本文关键字:其他 td 获取      更新时间:2023-09-26

好的,我有一个HTML表格,TR(tow(中有4个TD,如下代码所示:

<table>
   <tr>
      <td class="1">Lemon</td>
      <td class="2">Orange</td>
      <td class="3">Tea</td>
      <td class="4"><a href=#" class="get">Get</a></td>
   </tr>
   <tr>
      <td class="1">Apple</td>
      <td class="2">Tomato</td>
      <td class="3">Pineapple</td>
      <td class="4"><a href="#" class="get">Get</a></td>
   </tr>
</table>

我如何使用jQuery来制作,当点击#GET时,它将获得与它在同一表行中的类1、2、3的值。

例如,我点击第一行的#get,我会得到柠檬、橙子、茶作为结果。

我使用下面的jQuery代码,但它不起作用:

$(document).ready(function(){
 $('a#get').click(function(e){
    e.preventDefault();
    var val1 = $(this).parent().find('td.1').html();
    var val2 = $(this).parent().find('td.2').html();
    var val3 =  $(this).parent().find('td.3').html();
    alert(val1 + val2 + val3);
 });
});

关于我该怎么做或者我做错了什么,有什么想法吗?

谢谢!

请参阅工作演示

您应该使用唯一的id,这里是修改后的代码:

$(document).ready(function(){
 $('a.get').click(function(e){
    e.preventDefault();
    var val1 = $(this).closest('tr').find('td.1').html();
    var val2 = $(this).closest('tr').find('td.2').html();
    var val3 =  $(this).closest('tr').find('td.3').html();
    alert(val1 + val2 + val3);
 });
});

使用parent时,您将返回到td,因为链接在其中,您需要返回到通过closest('tr')完成的tr。此外,html已被修改为链接元素具有唯一id。

<a href=#" class="get">Get</a>

您在td元素内部调用.find(),而实际上您需要在tr中调用它,后者更高一级。

$(this).parent().find(...)替换为$(this).parent().parent().find(...)

(正如pimvdb所建议的,您应该使您的ID唯一。(

如果单元格只是数字的,那么在单元格中添加类是没有意义的——可以使用eq()

以下是我的做法:

$('#table-id tr').each(function() {
    var tds = $(this).find('td');
    $(this).find('a.get').click(function() {
        alert(tds.eq(0).html() + tds.eq(1).html() + tds.eq(2).html());
        return false;
    });
});