简体   繁体   English

使用 ctrlKey 设置触发 jQuery 3 事件

[英]Trigger a jQuery 3 Event with ctrlKey set

I'm about to update to jQuery 3 on Typescript with current Typedefinitions .我即将使用当前的Typedefinitions在 Typescript 上更新到 jQuery 3。

When compiling code like编译代码时

const event:JQuery.Event<HTMLElement, null> = $.Event("keydown");
event.which = 77;
event.ctrlKey = true;
$(window).trigger(event);

I get the following error我收到以下错误

TS2540: Cannot assign to 'ctrlKey' because it is a constant or a read-only property. TS2540:无法分配给“ctrlKey”,因为它是常量或只读属性。

How can I fix this?我该如何解决这个问题? This was no problem with jQuery 2 and wherever I look it's the recommended way to trigger an event with a set ctrlKey.这对 jQuery 2 来说没有问题,无论我在哪里看,它都是推荐的使用 set ctrlKey 触发事件的方法。

The only way to get around this compiler error is to rewrite it to解决此编译器错误的唯一方法是将其重写为

event["ctrl" + "Key"] = true;

but that feels way too hacky :) I'm looking for a smooth solution to this.但这感觉太hacky :) 我正在寻找一个平滑的解决方案。

The following now works as of @types/jquery@3.3.13 (fixed by DefinitelyTyped/DefinitelyTyped#29520 ).以下现在从@types/jquery@3.3.13 (已由DefinitelyTyped/DefinitelyTyped#29520 修复)。

const ev: JQuery.Event<Window> = $.Event("keydown");
ev.which = 77;
ev.ctrlKey = true;
$(window).trigger(ev);

For older versions, you would've had to use the following.对于旧版本,您将不得不使用以下内容。

const ev: JQuery.Event<Window> = $.Event("keydown", { ctrlKey: true });
ev.which = 77;
$(window).trigger(ev);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM