jQuery:覆盖单个元素的标记事件
jQuery: Override a tag event for a single element
所以我的所有表单都有这个常规提交事件:
$(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,跨浏览器保证的(,并且会停止在同一元素上附加的任何其他处理程序的执行(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>
您可以检测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;
}
});
您必须从其他人中排除 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;
}
相关文章:
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 将事件聚焦/模糊在可编辑内容的元素上
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 在IE8中不起作用的元素上触发单击事件
- 正在ng重复元素上添加事件
- 单击p元素时的javascript触发事件
- 存在每个时间元素的javascript事件
- Firefox:点击并更改未附加到文档树中的复选框元素上的事件
- 有没有一种方法可以让内联事件处理程序在元素创建后立即执行
- 将jQuery事件应用于所有类元素
- 在IE8上使用jQuery克隆HTML5元素和事件
- 单击其他元素时,我如何使用 jQuery 忽略更改事件
- 访问代码生成的输入元素上的keyup事件
- 如何查明鼠标按下事件是否发生在滚动条上或元素中的其他任何位置
- 当元素到达屏幕上的某个位置时触发事件
- Mootools:如何在点击时保持元素高亮显示并停止所有事件
- 将事件侦听器添加到文档,而不是签入元素存在,然后添加事件侦听器
- JQuery:使用clone()生成的元素不采用原始的事件属性
- 从其他元素上的单击事件访问image src属性
- 触发“三个”的点击事件.元素