当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Combining two event handlers, jQuery

问题描述:

I have two events that I want to observe on an object,

input.blur(function(event) {

ajaxSubmit(this);

event.preventDefault();

});

form.submit(function(event) {

ajaxSubmit(this);

event.preventDefault();

});

But I feel like this isn't dry enough, can I bind two events to my object input and execute my function ajaxSubmit() if either fire?


What would be super cool is if you could do:

input.bind("blur", "submit", function(event) {

ajaxSubmit(this);

event.preventDefault();

});

网友答案:

You can use the on method

$("#yourinput").on("blur submit", functionname);

Can combine any number of events; separate them with a space.

网友答案:

Yes, just declare the function and then bind it to the events:

var ajaxCallback = function(event){
  ajaxSubmit(this);
  event.preventDefault();
};

input.blur(ajaxCallback);
form.submit(ajaxCallback);

Note about variable declaration:

As @cletus points out, the way I declare the function provides a variable that is private to whichever scope it is defined in. I always program this way to minimize polluting the global namespace. However, if you are not defining both this callback and binding it to the elements in the same block of code, you should define it this way:

function ajaxCallback(event){ ... }

That way it is available wherever you later bind it using the .blur and .submit methods.

分享给朋友:
您可能感兴趣的文章:
随机阅读: