<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>
单击与每一行对应的按钮时,我希望我的脚本返回房间号,即该行的第一个单元格数据。在引用了互联网上的各种文章后,我尝试了很多东西。似乎什么都不起作用。请帮忙。
最佳答案
你可以使用类似的东西
$(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());
});
这里,选择器非常简单,我们首先在按钮上绑定(bind) click
事件,然后通过 onclick
选择 button
元素父级即 td
,我们选择 td
的父级,即 tr
,然后我们找到一个 class
为 .nr
为了更具体,您还可以编写 td.nr
而不仅仅是 .nr
。
您的行是动态添加的,为了让您的点击监听器正常工作,您必须 delegate the events
致谢@Patsy Issa用于建议 .siblings()
关于JavaScript - 获取所选表格行的第一个单元格的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25198699/