javascript - 如何从 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 (如预期的那样)。有没有办法引用按下按钮的行?
解决方案
这样做的推荐方式是不显眼的和委派的 - 给链接一个类:
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>
推荐阅读
- postgresql - 注意:下表中的一列或多列在 PostgreSQL 中没有统计错误
- javascript - 将十进制转换为二进制的最快方法 - Javascript
- javascript - 反应输入电话切换标志可见性
- c# - 与内部静态类的接口
- asp.net - Entity Framework Core 移除引用对象
- javascript - 在 Visual Studio 的发布版本中删除未使用的 css/js 代码
- html - 已分配但不可见的下拉菜单选项?
- javascript - Firefox 控制台中的 Konva 错误/警告
- linkedin - LinkedIn API v2 获取用户信息
- sql - 使用一个函数将计算值插入两个表中