我正在尝试获取包含许多可以单击的按钮的各个元素。例如,我想获取包含已单击按钮的表行。
在下面的代码中,单击将调用相应的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>
$(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>