문제

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:

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

Fiddle: http://jsfiddle.net/prZKy/

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?

도움이 되었습니까?

해결책

You can use dispatchEvent to programatically trigger events:

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.

Here is a fiddle of the code in action.

다른 팁

This should work:

var doubleClickEvent = document.createEvent('MouseEvents');
doubleClickEvent.initEvent('dblclick', true, true);
e.currentTarget.dispatchEvent(doubleClickEvent); // inside method
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top