HTML multiple events to trigger the same function

Is there a way to have multiple events (eg oninput, onblur) trigger exactly the same function in the HTML?

This is the HTML that I'm trying to simplify:

<input id="Email" name="Email" type="text" oninput="toggleSuccessIcon(this, isEmail)" onblur="toggleSuccessIcon(this, isEmail)">

I know this is possible in jQuery as explained here, but since I have a lot of different inputs (eg address, postcode, etc.) that need to call different functions (eg toggleSuccessIcon(this, isAddresss), toggleSuccessIcon(this, isPostCode), etc.) I wanted to avoid having a long and messy initialisation in the JavaScript. However, if I am being foolish by doing this in HTML rather than JQuery I'd appreciate an explanation as to the advantage of using JQuery.

Note that isEmail, isAddress, isPostCode, etc. is a function name.


你可以使用一个辅助函数

// events and args should be of type Array
function addMultipleListeners(element,events,handler,useCapture,args){
  if (!(events instanceof Array)){
    throw 'addMultipleListeners: '+
          'please supply an array of eventstrings '+
          '(like ["onblur","oninput"])';
  }
  //create a wrapper for to be able to use additional arguments
  var handlerFn = function(e){
    handler.apply(this, args && args instanceof Array ? args : []);
  }
  for (var i=0;i<events.length;i+=1){
    element.addEventListener(events[i],handlerFn,useCapture);
  }
}

function handler(e) {
  // do things
};

// usage
addMultipleListeners(document.getElementById('Email'),
                     ['oninput','onblur'],handler,false);

You can use data as:

<input class="configurable-events" type="text" data-events="blur focus click" data-function="myFunction" />
<input class="configurable-events" type="password" data-events="blur focus" data-function="myPasswordFunction" />

in jQuery you can use something like:

$('.configurable-events').each(function(){
    $(this).on($(this).data('events'), function(){
      $(this).data('function')($(this));
    });
});

function myFunction(myInput) {
  console.log(myInput.value());
}

function myPasswordFunction(myPasswordInput) {
  console.log(myPasswordInput.size());
}

$("input").on( "click blur", toggleSuccessIcon(this, isEmail));
链接地址: http://www.djcxy.com/p/96920.html

上一篇: 两个事件处理程序(click和mousemove)同时在一个元素上

下一篇: HTML多个事件触发相同的功能