how do I use jQuery to fire one common handler for more than one different events triggers?
On my web page I have two hyper links which do almost similar thing when an onclick event happens.开发者_开发技巧 Just to finish up I copy pasted the code twice and changed the event targets, so I essentially have code similar to this
$('#editprofilebutton').click(function(){/*do some magical stuff here*/});
$('#changepassbutton').click(function(){/*do some magical stuff here*/});
How can I remove this duplication and have some thing like $('#editprofilebutton' or '#changepassbutton').click(function(){/*do some magical stuff here*/});
?
$('#editprofilebutton, #changepassbutton').click(function(){/*do some magical stuff here*/});
Docs: Multiple Selector
Either:
$('#editprofilebutton, #changepassbutton').click(function() {
// do magical stuff
});
Or:
var doMagicalStuff = function() {
// do magical stuff
};
// now you can assign doMagicalStuff to as many elements as you want in as
// many different places as you want:
$('#editprofilebutton,#changepassbutton').click(doMagicalStuff);
// and you can assign it later on to another button if necessary. maybe you
// dynamically add a button that also needs to do magic. who doesn't want to
// do magic?
$('#someotherbutton').click(doMagicalStuff);
精彩评论