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

jQuery: Override a tag event for a single element

本文关键字:事件 元素 覆盖 单个 jQuery      更新时间:2023-09-26

所以我的所有表单都有这个常规提交事件:

$(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;
}