【问题标题】:JavaScript - Get data of first cell of clicked table row [duplicate]JavaScript - 获取单击的表格行的第一个单元格的数据[重复]
【发布时间】:2014-10-04 21:21:52
【问题描述】:
<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>

单击与每一行对应的按钮时,我希望我的脚本返回房间号,即该行的第一个单元格数据。在参考了网上各种文章后,我尝试了很多东西。似乎没有任何效果。请帮忙。我要求您不要发布任何 JQUERY 解决方案。只有 JAVASCRIPT。谢谢!

【问题讨论】:

    标签: javascript html dom javascript-events


    【解决方案1】:

    您可以将点击的元素传递给您的函数:

    <td><button type="button" class="mybutton" onclick="rowFunction(this)">Pay</button> </td>
    

    并遍历 DOM:

    function rowFunction(el) {
       var n = el.parentNode.parentNode.cells[0].textContent;
       // ...
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 HTML5 函数 document.querySelectorAll 获取按钮列表,然后向它们添加事件侦听器,以便您访问其父行并获取其第一个单元格。

      var buttons = document.querySelectorAll('#newtable tbody .mybutton');
      
      function buttonClicked(e) {
          var button = this,
              cell = button.parentElement,
              row = cell.parentElement,
              firstCell = row.querySelector('td');
          alert(firstCell.innerHTML);
      }
      
      for (var i = 0; i < buttons.length; i++) {
          buttons[i].addEventListener('click', buttonClicked);
      }
      

      Here is the fiddle I used to verify my code。此外,考虑使用 CSS 而不是 JavaScript 来设置行的颜色和悬停颜色。从长远来看,它将更清洁、更易于维护。

      【讨论】:

        【解决方案3】:

        使用喜欢

        $(".mybutton").click(function(){
            alert($(this).parent().siblings().eq(0).text());
        });
        

        DEMO

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-30
          • 1970-01-01
          • 2013-05-01
          • 2013-08-04
          • 2011-08-23
          相关资源
          最近更新 更多