如何在JavaScript中检查对象是否是KeyboardEvent?

时间:2017-03-17 15:14:25

标签: javascript

我想要一个接受事件作为参数的函数,并检查是否传递了有效的事件对象。

function doSomething(e){
  if(e is a keyboard event){
   // Proceed
  } else {
    console.log('Error: e is not a KeyboardEvent');
  }
}

typeof e只返回object。但是调试控制台清楚地显示了 KeyboardEvent ,所以它必须以某种方式可读。

3 个答案:

答案 0 :(得分:11)

Vanilla JS

instanceof运算符一样简单:

if (e instanceof KeyboardEvent){
  // it is a keyboard event!
}

来自MDN的解释:

  

instanceof运算符测试对象在其原型链中是否具有构造函数的prototype属性。

请注意,在处理多个(i)帧/窗口时,此运算符可能会很混乱,因为它们具有不同的上下文和不同的内置。但是在同一个窗口/框架中,这不是问题。

示例:

document.querySelector("#foo").addEventListener("keydown", (event)=>{
  console.log("event instanceof KeyboardEvent : ",event instanceof KeyboardEvent);
});
<label for="foo">edit input to check event type</label>
<input type="text" id="foo">

的jQuery

jQuery使用自己的实现包装本机事件:

  

jQuery的事件系统根据W3C标准规范化事件对象。保证事件对象被传递给事件处理程序(不需要检查window.event)。它规范化目标,relatedTarget,metaKey和pageX / Y属性,并提供stopPropagation()和preventDefault()方法。

source

但请注意,仍然可以通过event.originalEvent访问原生事件。您仍然可以测试event.typeevent.type==="keyup" || event.type==="keydown" || event.type === "keypress")。

示例:

$("#foo").on("keyup", (jqEvent) => {
  console.log("jqEvent instanceof KeyboardEvent : ", jqEvent instanceof KeyboardEvent); //false
  console.log("jqEvent.originalEvent instanceof KeyboardEvent : ", jqEvent.originalEvent instanceof KeyboardEvent); //true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="foo">edit input to check event type</label>
<input type="text" id="foo">

答案 1 :(得分:2)

试试这个if(e.type == 'keypress')

function doSomething(e){
  if(e.type == 'keypress'){
   // Proceed
  } else {
    console.log('Error: e is not a KeyboardEvent');
  }
}

答案 2 :(得分:2)

这适用于您的情况。

小心input-event它不是KeyboardEvent的实例。

&#13;
&#13;
function testEventType(e){
	console.log(e.type, e instanceof KeyboardEvent);
}

document.querySelector("#test").addEventListener('keypress', testEventType);
document.querySelector("#test").addEventListener('input', testEventType);
&#13;
<input id="test"/>
&#13;
&#13;
&#13;