簡體   English   中英

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>&#8377;<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM