首页 > 解决方案 > 点击后在 HTML 页面中查找外部元素

问题描述

我正在尝试获取包含许多可能被单击的按钮的相应元素。例如,我想获取包含已单击按钮的表格行。

在下面的代码中,单击会调用相应的 JavaScript,但“最近”返回的对象不是表格行之一。我也试过event.target代替这个,而parents不是closest但没有奏效。

$(".ok").on("click", function(event) {
  console.log("ok clicked! " + JSON.stringify(event));
  var row = $(this).closest("tr");
  console.log("event  = " + event.target.nodeName);
  console.log("outer type = " + typeof(row));
  console.log("outer id = " + row.id);
  console.log("outer  = " + JSON.stringify(row));
});
<table>
  <tr class="outer" id="id-1">
    <td>
      <button type="button" class="ok">B1</button>
    </td>
  </tr>
  <tr class="outer" id="id-2">
    <td>
      <button type="button" class="ok">B2</button>
    </td>
  </tr>
</table>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>

标签: javascriptjqueryclickclosest

解决方案


您可以使用jquery 的parent.parent方法来查找行,即 tr

$(document).ready(function(){
 $(".ok").on( "click", function( event ) {
        var row = $(this).parent().parent();
        console.log("event  = "+event.target.nodeName);
        console.log("outer type = "+typeof(row));
        console.log("outer id = "+row.attr("id"));
        console.log("outer  = "+JSON.stringify(row));
      });   
 })
<!doctype html>
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
  </head>
  <body>
    <table>
      <tr class="outer" id="id-1">
        <td>
          <button type="button" class="ok">B1</button>
        </td>
      </tr>       
      <tr class="outer" id="id-2">
        <td>
          <button type="button" class="ok">B2</button>
        </td>
      </tr>                 
    </table>
  </body>
</html>


推荐阅读