jQuery multiple events to trigger the same function

后端 未结 11 1076
青春惊慌失措
青春惊慌失措 2020-11-22 04:45

Is there a way to have keyup, keypress, blur, and change events call the same function in one line or do I have to do the

11条回答
  •  醉话见心
    2020-11-22 05:44

    It's simple to implement this with the built-in DOM methods without a big library like jQuery, if you want, it just takes a bit more code - iterate over an array of event names, and add a listener for each:

    function validate() {
      // ...
    }
    
    const element = document.querySelector('#element');
    ['keyup', 'keypress', 'blur', 'change'].forEach((eventName) => {
      element.addEventListener(eventName, validate);
    });
    

提交回复
热议问题