Bind a function on multiple jQuery elements at onc

2020-03-01 17:53发布

I have 3 jquery objects:

var a = $('.el1');
var b = $('.el2');
var c = $('.el3');

And I want to bind a "change" event to all of them at once, but I can't :(

$(a, b, c).bind('paste input change', function(){ ... }); simply doesn't work...

But if bind it to each element separately it works:

a.bind('...');
b.bind('...');
c.bind('...');

Is it possible to do this in a shorter way?

(And without passing the classes as selectors)

4条回答
Animai°情兽
2楼-- · 2020-03-01 18:20

$([a,b,c]).bind should work, as in:

var a = $('.el1');
var b = $('.el2');
var c = $('.el3');

$([a,b,c]).each(function(idx){
    $(this).bind('click', function(){
       alert($(this).text());
    });
});
查看更多
一夜七次
3楼-- · 2020-03-01 18:35

Try this:

$('.el1, .el2, .el3').bind(....)
查看更多
【Aperson】
4楼-- · 2020-03-01 18:44

Use $('.el1, .el2, .el3').bind(.....

Another solution is to combine them later:

var d = a;
d.add(b);
d.add(c);

d.bind(....

And if you don't like that either, if you would call the separate binds after all, you can choose to declare a named function once, and refer to that, instead of declaring the same anonymous inline function three times.

查看更多
疯言疯语
5楼-- · 2020-03-01 18:45

Use .add() [docs]:

a.add(b).add(c).bind(...
查看更多
登录 后发表回答