开发者

how do I use jQuery to fire one common handler for more than one different events triggers?

开发者 https://www.devze.com 2023-03-28 23:15 出处:网络
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 ess

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消