原生javascript for('click keyup')

时间:2015-12-11 15:16:40

标签: javascript

我希望将onclick,onkeyup绑定在一起并找出下面的原生JS版本。有人可以帮忙吗?

on("click keyup", ".searchButton",function(){
// code here
});

2 个答案:

答案 0 :(得分:1)

function addEvents(elm, events, handler){

    for(var i = 0 ;i< events.length; i++){

       elm.addEventListener( events[i] ,handler ,false); 

    }  
}

您必须将事件名称放在像var ev = ['click','keyup'];

这样的数组中

https://jsfiddle.net/f9dfjftk/

答案 1 :(得分:1)

本机解决方案可以使用具有className检查的全局侦听器,如:

function dosomething(ev){
  var tgt = ev.target;
  var log = document.getElementById('log');
  if( !tgt.classList.contains('something') ) {
    log.innerHTML += 'ignoring<br>';
    return true
  }
  log.innerHTML += tgt.tagName + ' ' + tgt.className + '<br>';
}
document.body.addEventListener('click',dosomething);
document.body.addEventListener('keyup',dosomething);
<button type="button" class="something">something</button>
<button type="button">not something</button>
<input type="text" class="something" placeholder="something">
<input type="text" placeholder="not something">
<div id="log"></div>