javascript 手动触发窗口对象上的事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24454583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:49:52  来源:igfitidea点击:

Manually trigger an event on window object

javascriptjquery

提问by Mark

I am adding a listener like so:

我正在添加一个这样的监听器:

    window.addEventListener('native.showkeyboard', function (e) {
        ...
        ...
    });

I'm writing a unit test for this so I want to trigger the event. Im doing:

我正在为此编写单元测试,因此我想触发该事件。我正在做:

    window.trigger('native.showkeyboard');

But I end up with an error for that line saying:

但我最终得到了该行的一个错误说:

    undefined is not a function

How can I manually trigger this event?

如何手动触发此事件?

EDIT

编辑

I have also tried:

我也试过:

  $(window).trigger('native.showkeyboard');

but the handler doesnt run with this as it's not registered with jquery...

但是处理程序没有运行这个,因为它没有用 jquery 注册......

回答by PeterKA

If you are triggering the event via jQuerythen the event ought to have been attached via jQuery-- see @fredericHamidi's comment.

如果您通过以下方式触发事件,jQuery则该事件应该通过以下方式附加jQuery- 请参阅@fredericHamidi 的评论。

$(window).on('native.showkeyboard', function (e) {
    .........
});

$(window).trigger('native.showkeyboard');

WORKING JSFIDDLE DEMO

工作 JSFIDDLE 演示

Or if you're using plain vanilla JS do it this way:

或者,如果您使用的是普通的 vanilla JS,请这样做:

window.addEventListener('native.showkeyboard', function (e) {
    ........
});

window.dispatchEvent( new Event('native.showkeyboard') );

WORKING JSFIDDLE DEMO

工作 JSFIDDLE 演示

回答by epascarello

well you are not working with a jQuery object...That would be your problem.

好吧,您没有使用 jQuery 对象...那将是您的问题。

 window.trigger('native.showkeyboard');  //<-- window is not a jQuery object

You need to wrap it

你需要把它包起来

 $(window).trigger('native.showkeyboard');