jquery on('click') handler for multiple elements referenced by vars

若如初见. 提交于 2019-12-02 03:29:09

问题


N.B. I'm aware that I add ids and combine these in a selector e.g. "#myDiv1,#myDiv2" so please refrain from suggesting this as it does not relate to my question.

Is there a way to 'chain' the vars below together in one on() declaration maybe as an array or something?

var myDiv1 = $('<div>Something here</div>');
var myDiv2 = $('<div>Something else here</div>');

myDiv1.on('click', function(){ doSomething();});
myDiv2.on('click', function(){ doSomething();});

I have a bunch of vars that I need to do some broad tracking of mouse events and it feels messy setting them up individually like the above example.


回答1:


  • You can pass an array of DOM elements to the jQuery function:

    $([
        myDiv1.get(0), 
        myDiv2.get(0)
    ]).on('click', function(){ doSomething();});
    

    jsFiddle Demo

  • Another possible way is to use the .add() method:

    myDiv1.add(myDiv2).on('click', function(){ doSomething();});
    

    jsFiddle Demo

  • Put them in an array, loop through them and attach the same handler. I made the example with ES5 forEach, but feel free to use a simple for loop or $.each.

    [cucc, gomb].forEach(function (el) {
        el.on('click', handler);
    });
    

    jsFiddle Demo

  • If they have a common ancestor, put a common class on them and use event delegation. Depending on the number of your elements, this could be the best solution performance-wise, because you only have to attach one handler to the common ancestor.

    $('.ancestor').on('click', '.common', handler);
    

    jsFiddle Demo



来源:https://stackoverflow.com/questions/20276215/jquery-onclick-handler-for-multiple-elements-referenced-by-vars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!