【问题标题】:jQuery - Getting the text value of a table cell in the same row as a clicked elementjQuery - 获取与单击的元素在同一行中的表格单元格的文本值
【发布时间】:2011-01-19 21:52:48
【问题描述】:

我单击表格单元格中的链接。我需要在同一表格行中获取特定单元格的值。

<tr>
    <td class="one">this</td>
    <td class="two">that</td>
    <td class="three">here</td>
    <td class="four"><a href="#">there</a></td>
</tr>
<tr>
    <td class="one">qwqw</td>
    <td class="two">dfgh</td>
    <td class="three">ui</td>
<td class="four"><a href="#">there</a></td>
</tr>

我有一个点击处理程序附加到第四个单元格中的链接。该单击处理程序调用一个打开模式窗口的函数。当提交模式中的表单时,我还想将 td class="two" 的值从单击链接的行传递到此模式。

这是发送模态的函数(问题区域正在为 var Something 获取正确的值):

var Send = function() {
    var Name = $( '#name' ).val();
    var Something = $(this).closest('td').siblings('.two').text(); // version 1. doesn't work
    var Something = $(this).closest('tr').siblings('td.two').text(); // version 2 also doesn't work
    var Something = $(this).attr('class'); // version 3. just a test but also doesn't work
    $.ajax( {
        async: false,
        data: { name: Name, somedata: Something },
        type: 'POST',
        url: the url
    });        
};

问题是我无法获得Something 的正确值。应该是与被点击元素在同一行的 td class=two 的值。

这一切结合在一起的方式是。单击目标链接,该链接调用名为 Send_Click() 的方法。 Send_Click 进行一些验证,然后调用 Send() 但从未填充 Something 的值。这是因为this 不是我想的那样吗?哎呀!

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    你想要.children() 而不是(documentation here):

    $(this).closest('tr').children('td.two').text();
    

    【讨论】:

    • 我怎样才能在这里使用像你这样的东西来解决我的问题:stackoverflow.com/questions/26004056/…(我在同一行中有一个链接,并在同一行中显示来自另一列的一些数据。
    【解决方案2】:

    尼克有正确的答案,但我想补充一下,您也可以在不需要类名的情况下获取单元格数据

    var Something = $(this).closest('tr').find('td:eq(1)').text();
    

    :eq(#) 具有从零开始的索引 (link)。

    【讨论】:

    • 我怎样才能在这里使用像你这样的东西来解决我的问题:stackoverflow.com/questions/26004056/…(我在同一行中有一个链接,并在同一行中显示来自另一列的一些数据。
    • 我正在寻找这个,它与 jQuery Mobile 配合得很好,谢谢!
    • 我更喜欢这种方法,因为我喜欢更少的依赖和更少的代码。
    【解决方案3】:

    它应该可以正常工作:

    var Something = $(this).children("td:nth-child(n)").text();
    

    【讨论】:

    • 我怎样才能在这里使用像你这样的东西来解决我的问题:stackoverflow.com/questions/26004056/…(我在同一行中有一个链接,并在同一行中显示来自另一列的一些数据。
    【解决方案4】:

    因此您可以使用 parent() 到达父 tr,然后使用 find 收集第二类的 td

    var Something = $(this).parent().find(".two").html();

    var Something = $(this).parent().parent().find(".two").html();

    根据 tr 行使用与 parent() 一样多的点击对象的深度

    希望这行得通...

    【讨论】:

      【解决方案5】:

      这也行

      $(this).parent().parent().find('td').text()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-24
        • 2011-03-28
        • 2012-12-12
        • 2013-05-01
        • 2012-06-25
        • 1970-01-01
        • 2022-06-17
        相关资源
        最近更新 更多