只有在与jQuery绑定时,jQuery才会触发keyup事件

时间:2022-04-03 00:02:59

Realy messed up with triggering keyup event using jQuery.

真的搞砸了用jQuery触发keyup事件。

Here is the clean example

这是一个干净的例子

http://jsfiddle.net/xQcGM/2/

http://jsfiddle.net/xQcGM/2/

When I type in any of input's, they both fire event, but when I try to fire it programmatically ($(element).trigger('event')) only the second one is triggered, but I expect both.

当我输入任何输入时,它们都是触发事件,但当我试图以编程方式触发时($(元素).trigger('event'),只有第二个触发,但我希望两者都触发。

Where do i miss something?

我在哪里错过了什么?

UPD I can't change the way handler was attached!

UPD我不能改变处理器连接的方式!

1 个解决方案

#1


6  

The native way to trigger events is to call dispatchEvent. Unfortunately, this method does not appear anywhere in jQuery's source. So I am guessing you have to either create the event objects yourselves and dispatch them manually.

触发事件的本机方式是调用dispatchEvent。不幸的是,这种方法在jQuery的源代码中没有出现。因此,我猜您必须自己创建事件对象并手动分派它们。

Here's a longer version with a working example.

这里有一个较长的示例。

$('button').click(function() {
        var myEvent = document.createEvent('KeyboardEvent');
        myEvent.initKeyboardEvent('keyup', true, true, null, false, 
                                false, false, false, 76, 0);
        $('input').each(function() {
            this.dispatchEvent(myEvent);
        });
    });

Or you could look at jQuery simulate plugin which makes it slightly easier. Here's a shorter version with another working example.

或者你也可以看看jQuery模拟插件,它会让你更轻松。这里有一个简短的版本,还有一个工作示例。

$('button').click(function() {
    $('input').simulate('keyup');
});

#1


6  

The native way to trigger events is to call dispatchEvent. Unfortunately, this method does not appear anywhere in jQuery's source. So I am guessing you have to either create the event objects yourselves and dispatch them manually.

触发事件的本机方式是调用dispatchEvent。不幸的是,这种方法在jQuery的源代码中没有出现。因此,我猜您必须自己创建事件对象并手动分派它们。

Here's a longer version with a working example.

这里有一个较长的示例。

$('button').click(function() {
        var myEvent = document.createEvent('KeyboardEvent');
        myEvent.initKeyboardEvent('keyup', true, true, null, false, 
                                false, false, false, 76, 0);
        $('input').each(function() {
            this.dispatchEvent(myEvent);
        });
    });

Or you could look at jQuery simulate plugin which makes it slightly easier. Here's a shorter version with another working example.

或者你也可以看看jQuery模拟插件,它会让你更轻松。这里有一个简短的版本,还有一个工作示例。

$('button').click(function() {
    $('input').simulate('keyup');
});