如何使用类选择器覆盖 id 选择器的 jQuery 事件处理程序?
我有几个带有 id 和类选择器的元素的单击事件处理程序:
$(function() {
$("#cancelOrderLink").click(function() {
if (confirm("If you continue, all items will be removed " +
"from your cart. This action cannot be undone. Continue " +
"and empty cart?"))
$("form#clearCartForm").submit();
});
$(".updateItemLink").click(function(){
$(this).closest("form").submit();
})
});
但是,我想添加逻辑以防止在元素具有特定类名时触发这些处理程序:
$(function() {
$(".superUser").click(function() {
$("#message").html("This action is not allowed when acting as a Super User.<br />");
return false;
});
});
如何使用第二个代码段覆盖第一个代码段中的处理程序片段?
I have click event handlers for several elements with id and class selectors:
$(function() {
$("#cancelOrderLink").click(function() {
if (confirm("If you continue, all items will be removed " +
"from your cart. This action cannot be undone. Continue " +
"and empty cart?"))
$("form#clearCartForm").submit();
});
$(".updateItemLink").click(function(){
$(this).closest("form").submit();
})
});
However, I want to add logic to prevent these handlers from being triggered if the element has a specific class name:
$(function() {
$(".superUser").click(function() {
$("#message").html("This action is not allowed when acting as a Super User.<br />");
return false;
});
});
How can I override the handlers in the first snippet with the second snippet?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
event.stopPropagation();
添加到您的代码中:或者,如果元素相等,并且您没有任何其他
click
侦听器,请取消绑定之前的方法:如果如果您想在运行时绑定特定 ID 的事件,而不是类名,请使用:
Add
event.stopPropagation();
to your code:Alternatively, if the elements are equal, and you don't have any other
click
listeners, unbind the previous method:If you want to bind the events at run-time for the specific IDs, but not the class name, use:
您可以使用
.not()
过滤器。You can use the
.not()
filter.我建议使用“return false”而不是 e.stopPropagation()。这是停止传播和防止违约的更万无一失的方法。
例如:
Instead of e.stopPropagation(), I would suggest using "return false". It is a more foolproof way to stop propagation and prevent defaults.
for example: