微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript-获取选定表行的第一个单元格的数据

<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>&#8377;<c:out value="${room.price}" /></td>
                            <td><button type="button" class="mybutton" onclick="rowFunction()">Pay</button> </td>
                        </tr>
                    </c:forEach>
                </table>

单击与每一行相对应的按钮后,我希望我的脚本返回房间号,即该行的第一个单元格数据.在参考了Internet上的各种文章之后,我尝试了很多事情.似乎没有任何作用.请帮忙.

解决方法:

您可以使用类似

Demo

$(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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。