javascript 如何以编程方式触发使用 addEventListener 定义的 dblclick 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18399215/
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
How to programmatically fire a dblclick event defined with addEventListener?
提问by Stilltorik
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:
对于 JS 单元测试,我需要检查双击行为是否符合预期。问题是该事件是通过 element.addEventListener 注册的。出于某种原因,在这种情况下, element.ondblclick() 不起作用。HTML:
<input type="image" src="pic.jpg" id="aa"/>
Javasript:
Java脚本:
document.getElementById('aa').addEventListener("dblclick", function(){alert('aa')});
document.getElementById('aa').ondblclick();
Fiddle: http://jsfiddle.net/prZKy/
小提琴:http: //jsfiddle.net/prZKy/
If you double click on the image, it works, but the ondblclick() in the javascript does not work.
如果双击图像,它可以工作,但 javascript 中的 ondblclick() 不起作用。
Anyone has an idea on how to do it?
任何人都知道如何做到这一点?
回答by CodingIntrigue
You can use dispatchEventto programatically trigger events:
您可以使用dispatchEvent以编程方式触发事件:
var event = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
document.getElementById('aa').dispatchEvent(event);
See the section "Triggering built-in events" on MDN.
请参阅MDN上的“触发内置事件”部分。
Hereis a fiddle of the code in action.
这是正在运行的代码的小提琴。
回答by Namish
This should work:
这应该有效:
var doubleClickEvent = document.createEvent('MouseEvents');
doubleClickEvent.initEvent('dblclick', true, true);
e.currentTarget.dispatchEvent(doubleClickEvent); // inside method

