我想要一个接受事件作为参数的函数,并检查是否传递了有效的事件对象.
function doSomething(e){ if(e is a keyboard event){ // Proceed } else { console.log('Error: e is not a KeyboardEvent'); } }
typeof e只返回对象.但是调试控制台清楚地显示了KeyboardEvent,所以它必须以某种方式可读.
解决方法
香草JS
与instanceof运算符一样简单:
if (e instanceof KeyboardEvent){ // it is a keyboard event! }
MDN的解释:
The
instanceof
operator tests whether an object has in its prototype chain the prototype property of a constructor.
请注意,在处理多个(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’s event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target,relatedTarget,which,MetaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods.
但请注意,仍然可以通过event.originalEvent访问本机事件.你仍然可以测试event.type(event.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">