adding multiple event listeners to one element

后端 未结 14 1465
夕颜
夕颜 2020-11-27 13:12

So my dilemma is that I don\'t want to write the same code twice. Once for the click event and another for the touchstart event.

Here is the original co

14条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 13:41

    I know this is an old question, but I thought some might find this approach useful; it could be applied to any similarly repetitive code:

    ES6

    ['click','ontouchstart'].forEach( evt => 
        element.addEventListener(evt, dosomething, false)
    );
    

    ES5

    ['click','ontouchstart'].forEach( function(evt) {
        element.addEventListener(evt, dosomething, false);
    });
    

提交回复
热议问题