jQuery:覆盖单个元素

时间:2016-07-24 09:57:19

标签: javascript jquery events

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

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

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

3 个答案:

答案 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;
}