我一直在研究此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>
我的目标是在当前表行内单击按钮时获取(“最靠近,上方”)表行按钮的ID(对不起,这有点令人困惑)
我这样使用jQuery:
function get(elm,pid){
alert($.nid=$(elm).closest('tr').prev("tr[pid='"+pid+"']").find('button').attr('id'));
}
我发现,如果这些行位于另一行之上,那么就可以毫无问题地获取上一行中的按钮的id。
但是,如果该行位于上方,则无法获取值;逻辑上有什么问题?我要去哪里错了?
请在这里找到我的解释小提琴:
.prev()
方法选择前一个同级元素。如果传递选择器,则只有与指定选择器匹配时,它才会选择前一个同级。
假设您单击第四个按钮。该get
函数的第二个参数是p1
,因为tr
与指定的选择器不匹配jQuery返回一个空的集合,因此attr
返回undefined
。
如果我正确理解了这个问题,您希望选择tr
相同的问题pid
。您可以使用.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-*
属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句