【问题标题】:Not able to get Previous row attributes in Html Table无法在 Html 表中获取上一行属性
【发布时间】:2015-04-18 09:12:00
【问题描述】:

我一直在研究这个 Html 表结构:

<table>
    <tr id='1' pid='p3'><td><button id='1' onClick="get(this,'p3')">1</button></td></tr>
    <tr id='2' pid='p3'><td><button id='2' onClick="get(this,'p3')">2</button></td></tr>
    <tr id='3' pid='p2'><td><button id='3' onClick="get(this,'p2')">3</button></td></tr>
    <tr id='4' pid='p1'><td><button id='4' onClick="get(this,'p1')">4</button></td></tr>
    <tr id='5' pid='p2'><td><button id='5' onClick="get(this,'p2')">5</button></td></tr>
    <tr id='6' pid='p2'><td><button id='6' onClick="get(this,'p2')">6</button></td></tr>
</table>

我的目标是在单击当前表格行内的按钮时获取('closest , above')表格行按钮的 id(抱歉,这有点令人困惑)

我就是这样使用 jQuery 的:

function get(elm,pid){
    alert($.nid=$(elm).closest('tr').prev("tr[pid='"+pid+"']").find('button').attr('id'));
}

我发现如果这些行位于另一行之上,则可以毫无问题地获取上一行中按钮的 ID。

但是如果该行更远,则无法获取值;逻辑有什么问题?我哪里错了?

请在此处找到我的解释性小提琴:

http://jsfiddle.net/jtYDP/386/

【问题讨论】:

    标签: jquery html-table


    【解决方案1】:

    .prev() 方法选择 first 前一个兄弟元素。如果你传递一个选择器,它只会选择与指定选择器匹配的前一个兄弟。

    假设您单击第四个按钮。 get 函数的第二个参数是p1,因为tr 与指定的选择器不匹配 jQuery 返回一个空集合,因此attr 返回undefined

    如果我正确理解了这个问题,您想选择具有相同pid 的前一个tr。您可以使用.prevAll().first() 方法。

    $('tr button').on('click', function() {
        var $row = $(this).closest('tr'),
            pid = $row.attr('pid');
    
        var id = $row.prevAll("tr[pid='"+pid+"']")
                     .first() 
                     .find('button')
                     .attr('id');
    });
    

    注意,ID 必须是唯一的。而pid 不是有效属性。您可以改用data-* 属性。

    【讨论】:

    • 在jquery中有没有可能的解决方案
    • @athon 如果您单击第四个按钮,您会期待什么?应该提醒什么值?
    • 显示未定义的第四个按钮是可以的,因为它没有任何以前的 pid。但是如果我单击具有相同 pid 的最接近的上一个按钮的第五个按钮 id,应该会收到警报。我已经在小提琴中解释过了。
    • 非常感谢 Vohunam .. prevAll().first() 为我工作 :) Soo 对不起,我无法投票支持你的努力,我的代表太低了,不能这样做.. 我会尽快我可以..
    • @athon 不客气,真的!我很高兴能提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 2016-06-26
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    相关资源
    最近更新 更多