<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" onm ouSEOver="this.bgColor='gold';" onm ouSEOut="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上选择按钮元素的父元素,即td,然后选择td的父元素,即tr,然后我们找到一个类为.nr的元素
您也可以编写td.nr而不是.nr来更具体.
您的行正在动态添加,为了使您的点击侦听器正常工作,您将不得不delegate the events
由于建议.siblings()而归功于@Patsy Issa