JavaScript - 获取所选表格行的第一个单元格的数据 [英] 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 i.e. the first cell data of the row. I have tried a lot of things after referring various articles on the Internet. Nothing seems to work. Please help.
推荐答案
您可以使用
$(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());
});
这里选择器很简单,我们先绑定点击
事件在按钮上,而
onclick
我们选择按钮
元素父代ie td
,我们选择 td
的父母,即 tr
然后我们找到一个元素一个类
.nr
Here, the selector is pretty simple, we are first binding click
event on the button, and onclick
we select the button
element parent i.e td
and we select the parent of td
i.e tr
and later we find an element with a class
of .nr
你也可以写入 td.nr
而不是 .nr
更具体。
You can also write td.nr
instead of just .nr
to be more specific.
您的行正在动态添加,为了让您的点击监听器工作,您必须使用委托事件
Your rows are being dynamically added, in order for your click listener to work you will have to delegate the events
信用到 @ Patsy Issa ,以建议 .siblings()
这篇关于JavaScript - 获取所选表格行的第一个单元格的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!