Jsu*_*alv 0 javascript jquery event-delegation
我正在使用jQuery的事件委托将click事件添加到表行.我在行的第一个td中也有一个复选框.当我点击行中的任何地方时,一切都按预期工作.但是,当我单击复选框时,我不希望该事件有效.我尝试过使用:not()选择器,但也许我错过了一些东西,因为当我点击复选框时我仍在触发事件.
HTML
<tr>
<td>
<div class="myCheckbox"><input type="checkbox" name="userName" /></div>
</td>
<td><a href="/go/to/user/profile"></a></td>
<td>more info</td>
<td>more info</td>
<td>more info</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
jQuery的
$('table tr:not(':checkbox')').on('click', 'td', function(event) {
// Do something
});
Run Code Online (Sandbox Code Playgroud)
我可以获得帮助来解决我想要做的事吗?
两个选项(都涉及tr:not从现有代码中删除内容,正如您所说的那样不起作用 - tr元素不能是复选框,并:not检查元素,而不是其内容):
向调用的复选框添加事件处理程序e.stopPropagation.然后点击事件将不会到达该行.您可以直接或通过委派来实现.这是一个直接的实例.如果你是间接的,请务必label在你想要支持的所有浏览器上测试点击s来激活复选框(如果你想要的话).
要么
将此添加到您的处理程序:
if ($(event.target).is('input[type=checkbox]')) {
return;
}
Run Code Online (Sandbox Code Playgroud)
例如:
$('table').on('click', 'td', function(event) {
if ($(event.target).is('input[type=checkbox]')) {
return;
}
// Logic here
});
Run Code Online (Sandbox Code Playgroud)
这可以通过测试事件的来源来查看它是否是一个复选框,并提前纾困.
在这两种情况下,如果使用a label来激活复选框,则可能需要对标签执行相同的操作.
我好奇会是什么样#2像处理labels,而事实证明它是足够的代码进入一个功能,但不硬&MDASH可能我怎么会去:活生生的例子 | 资源
jQuery(function($) {
// The table cell click handler
$("table").on("click", "td", function(e) {
// Is the source a checkbox or the label for
// one?
if (isCheckbox($(e.target))) {
return;
}
// Normal handling
$(this).toggleClass("foo");
});
// Function to test whether the source is a
// checkbox, or the label of a checkbox
function isCheckbox($elm) {
var chkid;
if ($elm.is("input[type=checkbox]")) {
return true;
}
if ($elm.is("label")) {
chkid = $elm.attr("for");
if (chkid) {
return $("#" + chkid).is("input[type=checkbox]");
}
return !!$elm.find("input[type=checkbox]")[0];
}
return false;
}
});
Run Code Online (Sandbox Code Playgroud)