如何以编程方式触发使用addEventListener定义的dblclick事件? [英] How to programmatically fire a dblclick event defined with addEventListener?

查看:1365
本文介绍了如何以编程方式触发使用addEventListener定义的dblclick事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于JS Unit测试,我需要检查双击是否按预期进行操作。问题是事件是通过element.addEventListener注册的。由于某种原因,在这种情况下,element.ondblclick()不起作用。
HTML:

For JS Unit test, I need to check that a double-click behaves as expected. The issue is that the event was registered via element.addEventListener. And for some reason, in this case, element.ondblclick() does not work. HTML:

<input type="image" src="pic.jpg" id="aa"/>

Javasript:

Javasript:


document.getElementById('aa').addEventListener("dblclick", function(){alert('aa')});
document.getElementById('aa').ondblclick();

小提琴: http://jsfiddle.net/prZKy /

如果您双击图片,它可以工作,但javascript中的ondblclick()不起作用。

If you double click on the image, it works, but the ondblclick() in the javascript does not work.

任何人都有一个如何做的想法?

Anyone has an idea on how to do it?

推荐答案

你可以使用 dispatchEvent 以编程方式触发事件:

You can use dispatchEvent to programatically trigger events:

var event = new MouseEvent('dblclick', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
document.getElementById('aa').dispatchEvent(event);

请参阅 MDN

这里是执行代码的小提琴。

Here is a fiddle of the code in action.

这篇关于如何以编程方式触发使用addEventListener定义的dblclick事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆