adding multiple event listeners to one element

后端 未结 14 1473
夕颜
夕颜 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:47

    I have a small solution that attaches to the prototype

      EventTarget.prototype.addEventListeners = function(type, listener, options,extra) {
      let arr = type;
      if(typeof type == 'string'){
        let sp = type.split(/[\s,;]+/);
        arr = sp;   
      }
      for(let a of arr){
        this.addEventListener(a,listener,options,extra);
      }
    };
    

    Allows you to give it a string or Array. The string can be separated with a space(' '), a comma(',') OR a Semicolon(';')

提交回复
热议问题