简体   繁体   中英

jQuery make .change and .click event for different element to call same function

I googled but most of them is to bind different event for SAME element.

For

$('#a').change(function() {
     /bla
     /bla
});

$('#b').click(function(){
     /bla
     /bla
});

I want something like this

$('#a').change OR ('#b').click(function(){
     /bla
     /bla
});

Try this:

var func = function(){
     /bla
     /bla
};

$('#a').change(func);
$('#b').click(func);

Why not just put the code you want to reuse in a function and, well, reuse it?

function doSomething() {
  // bla
}

Then...

$('#a').change(function() {
     doSomething();
});

$('#b').click(function(){
     doSomething();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM