gpt4 book ai didi

javascript - 如何检查对象是否是 JavaScript 中的 KeyboardEvent?

转载 作者:数据小太阳 更新时间:2023-10-29 04:59:54 24 4
gpt4 key购买 nike

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

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

typeof e 只返回 object。但是调试控制台清楚地显示了 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)frame/windows 时可能会很困惑,因为它们具有不同的上下文和不同的内置函数。但在同一个窗口/框架中,这不是问题。

示例:

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.

source

但请注意,原生事件仍可通过 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">

关于javascript - 如何检查对象是否是 JavaScript 中的 KeyboardEvent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42861107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com