javascript jQuery 触发 mousedown 由 addEventListener 注册

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24357819/
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:37:46  来源:igfitidea点击:

jQuery trigger mousedown registered by addEventListener

javascriptjqueryjavascript-events

提问by Sam

I want to simulate fake mousedown event by jQuery trigger() method, and I register mousedown event by native javascript method - addEventListener(). And I found it can't be triggered...

我想通过 jQuery trigger() 方法模拟假的 mousedown 事件,并通过本机 javascript 方法 - addEventListener() 注册 mousedown 事件。我发现它无法触发...

elem.addEventListener('mousedown', function () {
    alert('addEventListener');
});
$(elem).on('mousedown', function () {
    alert('on');
});
$(elem).trigger('mousedown');

Sample in jsFiddle

jsFiddle 中的示例

I do some tests about it.

我对此做了一些测试。

  1. Register mousedown event by jQuery on()
    • Result: works
  2. Register clickevent by addEventListener()
    • Result: works
  1. 通过jQuery on()注册 mousedown 事件
    • 结果:有效
  2. 通过 addEventListener()注册点击事件
    • 结果:有效

Is anything wrong here?

这里有什么问题吗?

Thanks.

谢谢。

P.S. The reason why uses addEventListener() is that I want to write a library without jQuery.

PS 之所以使用 addEventListener() 是因为我想写一个没有 jQuery 的库。

回答by Okky

Try using

尝试使用

EventTarget.dispatchEvent

MDN link

MDN链接

Your code will be something like

您的代码将类似于

var elem = document.getElementById('square');
elem.addEventListener('mousedown', function () {
    alert('addEventListener');
});
$(elem).on('mousedown', function () {
    alert('on');
});

elem.dispatchEvent(new Event('mousedown'))

You might have to use fireEventif you are considering IE.

fireEvent如果您正在考虑使用 IE,则可能必须使用。

object.fireEvent(bstrEventName, pvarEventObject, pfCancelled) 

MSDN link

MSDN链接

It would be like

就像

if (document.createEvent) {
    element.dispatchEvent(event);
} else {
    element.fireEvent("on" + event.eventType, event);
}

回答by Maulik Anand

Jquery Only triggers the events that created by itself

jquery 只触发自己创建的事件

Even the order is also matters like : this Works

甚至顺序也很重要:this Works

$(elem).on('mousedown', function () {
    alert('on');
});
$(elem).trigger('mousedown');

But Below code Will not Work

但下面的代码不起作用

 $(elem).trigger('mousedown');
 $(elem).on('mousedown', function () {
    alert('on');
});

Take A look at This DEMO FIDDLE

看看这个演示小提琴