首页 > 解决方案 > 如何从 html 事件传递(或引用)“$(this)”?

问题描述

假设我在表格中有一个按钮,可以向表格添加新行:

<td><a onclick="addRow()"></a></td></tr>...

我想参考$(this)$(this).closest('tr')从页面底部的功能。

function addRow(){
   $(this) // contains all information from the row which pressed the button

}

简单地从 HTML 传递一个 javascript 变量将导致 null (如预期的那样)。有没有办法引用按下按钮的行?

标签: javascriptjquery

解决方案


这样做的推荐方式是不显眼的和委派的 - 给链接一个类:

var $tb = $("#someTable");

$tb.on("click", ".addRow", function(e) { // delegation to allow new rows' links to work
  e.preventDefault(); // stop any click side effects
  var $row = $(this).closest("tr");
  $tb.append($row.clone())
});
a { text-decoration:none }
td,th { padding:3px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>Add</th>
    </tr>
  </thead>
  <tbody id="someTable">
    <tr>
      <td>1st</td>
      <td>2nd</td>
      <td><a class="addRow" href="#">+</a></td>
    </tr>
    <tr>
      <td>3rd</td>
      <td>4th</td>
      <td><a class="addRow" href="#">+</a></td>
    </tr>
  </tbody>
</table>


推荐阅读