单击后在HTML页面中查找外部元素

问题描述 投票:0回答:1

我正在尝试获取包含许多可以单击的按钮的各个元素。例如,我想获取包含已单击按钮的表行。

在下面的代码中,单击将调用相应的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/[email protected]/dist/jquery.min.js"></script>
javascript jquery click closest
1个回答
0
投票
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/[email protected]/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>
© www.soinside.com 2019 - 2024. All rights reserved.