[英]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.