如何使用jQuery为多个不同的事件触发器触发一个公共处理程序?

时间:2011-08-17 15:54:20

标签: javascript jquery

在我的网页上,我有两个超级链接,当onclick事件发生时,它们几乎完全类似。只是为了完成我复制粘贴代码两次并更改事件目标,所以我基本上有类似于这个

的代码
$('#editprofilebutton').click(function(){/*do some magical stuff here*/});
$('#changepassbutton').click(function(){/*do some magical stuff here*/});

如何删除此重复项并使用$('#editprofilebutton' or '#changepassbutton').click(function(){/*do some magical stuff here*/});

之类的内容

2 个答案:

答案 0 :(得分:2)

$('#editprofilebutton, #changepassbutton').click(function(){/*do some magical stuff here*/});

文档:Multiple Selector

答案 1 :(得分:1)

或者:

$('#editprofilebutton, #changepassbutton').click(function() {
    // do magical stuff
});

或者:

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