gpt4 book ai didi

javascript - jQuery:覆盖单个元素的标记事件

转载 作者:行者123 更新时间:2023-11-29 15:26:41 26 4
gpt4 key购买 nike

所以我的所有表单都有这个一般提交事件:

$(document).on('submit','form',function(e){
e.preventDefault();
console.log('You submitted a form!');
//here I would put a simple ajax form submit
return false;
}

现在我有一个不应该触发上述事件的特殊表单。
相反,它应该只触发此事件:

$(document).on('submit','#SpecialForm',function(e){
e.preventDefault();
console.log('You submitted the special form!');
//here I would put a special ajax form submit
return false;
}

如何做到这一点?如果可能,不修改第一个事件。

最佳答案

既然你说过你不想修改你的第一个处理程序,这里有几个避免这样做的选项:

1.如果您在第一个处理程序之前注册了第二个处理程序,您可以通过以下方式停止它

event.stopImmediatePropagation();

...因为处理程序按照它们附加的顺序执行(这由 jQuery 保证,跨浏览器)并且停止执行附加在同一元素上的任何其他处理程序(文档).

// Note that this one must be first if they're on
// the same element
$(document).on("click", "#foo", function(e) {
console.log("foo click");
e.stopImmediatePropagation();
return false;
});
$(document).on("click", "div", function() {
console.log("main click");
});
Click each of the following divs:
<div>main</div>
<div id="foo">foo</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

2。或者在 document.body 而不是 document 上注册它,因为 document.body 将在 document 和您的表单之间:

$(document).on('submit','#SpecialForm',function(e){

...并且您现有的return false 将阻止从document.body 传播到document

// Note that this one must be first if they're on
// the same element
$(document).on("click", "div", function() {
console.log("main click");
});
$(document.body).on("click", "#foo", function(e) {
console.log("foo click");
return false;
});
Click each of the following divs:
<div>main</div>
<div id="foo">foo</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于javascript - jQuery:覆盖单个元素的标记事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38550785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com