所以我的所有表格都有这个一般提交事件:
$(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;
}
如何做到这一点?如果可能的话,不修改第一个事件。
答案 0 :(得分:1)
既然你已经说过不想要修改你的第一个处理程序,这里有几个选项可以避免这样做:
1。如果您在第一个处理程序之前注册了第二个处理程序,则可以通过
停止它event.stopImmediatePropagation();
...因为处理程序按照它们附加的顺序执行(这由jQuery,跨浏览器保证)并且停止执行附加在同一元素(document
)上的任何其他处理程序。
// 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>
答案 1 :(得分:1)
您可以检测event's target
并触发相应的功能:
$(document).on('submit', 'form', function(e) {
e.preventDefault();
if (e.target.id == 'SpecialForm') {
console.log('You submitted the special form!');
//here I would put a special ajax form submit
return false;
} else {
console.log('You submitted a form!');
//here I would put a simple ajax form submit
return false;
}
});
答案 2 :(得分:-1)
你必须从其他人那里排除SpecialForm ......所以你的第一个功能应该是:
$(document).on('submit','form:not(#SpecialForm)',function(e){
e.preventDefault();
console.log('You submitted a form!');
//here I would put a simple ajax form submit
return false;
}