[英]How to get row of element in cell by javascript/jquery?
I have a simple table like this 我有一个像这样的简单桌子
<table id="tempTable">
<tbody>
<tr id="row_01">
<td>
<button onclick="btnclick(this);" >Save Row</button>
</td>
</tr>
<tr id="row_02">
<td>
<button onclick="btnclick(this);" >Save Row</button>
</td>
</tr>
</tbody>
</table>
function btnclick(e) {
var currentRow = $(e).parent().parent();
alert(currentRow.id);
}
I want to determine which row where the button clicked was placed. 我想确定单击按钮所在的行。 So I use some jquery method in btnclick() as you see abow.
因此,如您所见,我在btnclick()中使用了一些jquery方法。 But sometime I don't know how deep level the button was placed in row (), so Im looking for a way to get an ancestor by tag
<tr>
of a element. 但是有时我不知道按钮在行()中的放置深度,所以我正在寻找一种通过元素的标签
<tr>
获取祖先的方法。
Anybody help me, thanks? 有人帮助我,谢谢吗?
Try this : 尝试这个 :
function btnclick(e) {
var currentRow = $(e).closest('tr');
alert(currentRow.id);
}
The closest()
function will return the closest ancestor referenced by its selector. closest()
函数将返回其选择器引用的最接近的祖先。 In this case the selector is simple a <tr>
element. 在这种情况下,选择器只是一个
<tr>
元素。
Taken from the jQuery docs : 取自jQuery docs :
.closest( selector )
.closest(选择器)
Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
获取与选择器匹配的第一个元素,从当前元素开始,一直到DOM树。
A better method could be used if you change your HTML a little bit. 如果你改变你的HTML一点点可以使用更好的方法。 If you placed the same class on each of your buttons.
如果您在每个按钮上都放置了相同的类。
Eg : 例如:
<td>
<button class="myBtnClass" >Save Row</button>
</td>
Then your jQuery would look like this : 然后您的jQuery将如下所示:
$(".myBtnClass").on('click',function(){
var currentRow = $(this).closest('tr');
alert(currentRow.attr('id'));
});
This function will capture a click on any element with the .myBtnClass
class. 此函数将捕获对
.myBtnClass
类的任何元素的单击。
The jQuery way is: jQuery的方式是:
$('#tempTable').find('button').click(function() {
var currentRow = $(this).closest('tr');
});
how about using closest 如何使用最接近的
function btnclick(e) {
var currentRow = $(e).closest('tr');
alert(currentRow.id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.