javascript - 点击后在 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>
解决方案
您可以使用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>
推荐阅读
- flutter - 如何导航到屏幕并删除所有溃败历史[退出功能]
- javascript - 如何从字符串(在网站上)编写正确的列表?
- visual-studio-code - 由于 Nmake 错误,Raspberry pico 无法编译
- java - 上传时握手期间远程主机关闭连接
- mybatis - Mybatis insert into ... select from ... 返回主键
- pandas - 根据 2 个 pandas 列的比较在 matplotlib 中绘制一条线
- discord - 我如何制作一个响应特定用户的机器人?不和谐.py
- c# - 在excel中更快地读取数据行的问题
- powerbi - 在直接查询模式下下载 Power BI 中的数据集块
- javascript - 将 ID 分配给为数据表动态创建的选项