[英]JavaScript - Get data of first cell of selected table row
<table border="1" cellpadding="5" id="newtable">
<tr>
<th>Room No</th>
<th>AC</th>
<th>Deluxe</th>
<th>Tariff</th>
</tr>
<c:forEach var="room" items="${myrooms}">
<tr bgcolor="#4B476F" onMouseOver="this.bgColor='gold';" onMouseOut="this.bgColor='#4B476F';">
<td class="nr"><c:out value="${room.roomno}" /></td>
<td><c:out value="${room.ac}" /></td>
<td><c:out value="${room.deluxe}" /></td>
<td>₹<c:out value="${room.price}" /></td>
<td><button type="button" class="mybutton" onclick="rowFunction()">Pay</button> </td>
</tr>
</c:forEach>
</table>
On clicking the button corresponding to every row, I want my script to return the Room number ie the first cell data of the row. 在单击与每一行相对应的按钮时,我希望我的脚本返回房间号,即该行的第一个单元格数据。 I have tried a lot of things after referring various articles on the Internet.
在参考了Internet上的各种文章之后,我尝试了很多事情。 Nothing seems to work.
似乎没有任何作用。 Please help.
请帮忙。
You can use something like 您可以使用类似
$(window).on('click', '.mybutton' ,function() {
alert($(this).parent().parent().find('.nr').text());
//Or you can use, which is even better
//alert($(this).parent().siblings('.nr').text());
});
Here, the selector is pretty simple, we are first binding click
event on the button, and onclick
we select the button
element parent ie td
and we select the parent of td
ie tr
and later we find an element with a class
of .nr
在这里,选择器非常简单,我们首先在按钮上绑定
click
事件,然后在onclick
选择button
元素的父元素,即td
然后选择td
的父元素,即tr
,然后我们找到一个.nr
class
的元素
You can also write td.nr
instead of just .nr
to be more specific. 你也可以写
td.nr
而不是仅仅.nr
更加具体。
Your rows are being dynamically added, in order for your click listener to work you will have to delegate the events 您的行是动态添加的,为了使您的点击侦听器正常工作,您必须委派事件
Credits to @Patsy Issa for suggesting .siblings()
感谢@Patsy Issa建议
.siblings()
$(".mybutton").click(function(){
alert($(this).parent().siblings().eq(0).text());
});
通常我使用DataTables js作为解决方案,可以在以下位置进行检查: https : //datatables.net/reference/api/row().data()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.