[英]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>
在单击与每一行相对应的按钮时,我希望我的脚本返回房间号,即该行的第一个单元格数据。 在参考了Internet上的各种文章之后,我尝试了很多事情。 似乎没有任何作用。 请帮忙。
您可以使用类似
$(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());
});
在这里,选择器非常简单,我们首先在按钮上绑定click
事件,然后在onclick
选择button
元素的父元素,即td
然后选择td
的父元素,即tr
,然后我们找到一个.nr
class
的元素
你也可以写td.nr
而不是仅仅.nr
更加具体。
您的行是动态添加的,为了使您的点击侦听器正常工作,您必须委派事件
感谢@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.