Bind a function on multiple jQuery elements at once

前端 未结 4 2059
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-04 19:46

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 the

相关标签:
4条回答
  • 2021-01-04 20:25

    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.

    0 讨论(0)
  • 2021-01-04 20:27

    $([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());
        });
    });
    
    0 讨论(0)
  • 2021-01-04 20:32

    Try this:

    $('.el1, .el2, .el3').bind(....)
    
    0 讨论(0)
  • 2021-01-04 20:48

    Use .add() [docs]:

    a.add(b).add(c).bind(...
    
    0 讨论(0)
提交回复
热议问题