最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML multiple events to trigger the same function - Stack Overflow

programmeradmin7浏览0评论

Is there a way to have multiple events (e.g. 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 (e.g. address, postcode, etc.) that need to call different functions (e.g. 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.

Is there a way to have multiple events (e.g. 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 (e.g. address, postcode, etc.) that need to call different functions (e.g. 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.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Apr 22, 2015 at 6:14 TarostarTarostar 1,3161 gold badge17 silver badges31 bronze badges 3
  • 3 i belive its a bigger mess to mix js with html – madalinivascu Commented Apr 22, 2015 at 6:17
  • You can attach events through addEventListener in JavaScript or in much cleaner way using jQuery. – Sandeep Nayak Commented Apr 22, 2015 at 6:21
  • All the inputs actually use "toggleSuccessIcon", but the second and optional third parameter varies from input to input, e.g. <input id="Address" name="Address" type="text" oninput="toggleSuccessIcon(this, hasContent, 5)" onblur="toggleSuccessIcon(this, hasContent, 5)"> – Tarostar Commented Apr 22, 2015 at 6:45
Add a comment  | 

4 Answers 4

Reset to default 3

You could use a helper function

// 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));

I know this is so massively late, but I thought I'd throw my hat in the ring anyway. When I have numerous events that need to trigger the same thing, it feels so wasteful to do 3-5 eventListeners, so what I do is making a forEach-loop on an array that holds the event-names in vanilla JS. I wish though, that the eventListener could accept an array as a name directly, but here we are.

    const element = document.getElementById('Email');

    ['input', 'blur'].forEach(eventName =>{
        element.addEventListener(eventName, event=>{
            // Your eventcode goes here.
        });
    });
发布评论

评论列表(0)

  1. 暂无评论