如何从QUnit测试中触发本机Javascript事件? [英] How can I trigger a native Javascript event from a QUnit test?
问题描述
我正在开发一个不依赖于jQuery的Javascript库,尽管我的测试中有jQuery和QUnit可用。在库中,我按照jQuery的方式将事件附加到元素:
I'm working on a Javascript library that does not depend on jQuery, though I have jQuery and QUnit available in my tests. In the library, I attach an event to an element the way jQuery does:
if (document.addEventListener) {
tab.addEventListener('click', MyModule.show, false);
} else if (document.attachEvent) {
tab.attachEvent('click', MyModule.show);
}
我试过调用 $('#tab') .click();
在我的QUnit测试中,但它不会导致我的事件处理程序被调用。
I tried calling $('#tab').click();
in my QUnit test, but it doesn't cause my event handler to be called.
推荐答案
jQuery有自己的事件注册系统,它与DOM的事件注册分开。当我们调用 $(某事物).click()
时,所有已注册的jQuery处理程序和已注册的 onclick
处理程序将被触发,但没有别的。例如,
jQuery has its own event registration system, which is separate from the DOM's event registration. When we call $(something).click()
, all registered jQuery handlers and the registered onclick
handler will fire, but nothing else would. For example,
document.body.addEventListener('click', function() { alert('event') }, false);
document.body.onclick = function() { alert('onclick'); };
$('body').click(); // alerts "onclick"
如果你打电话给 document.body.onclick( )
,然后只有第二个事件将触发并警告onclick。要同时触发两个事件,请创建一个事件对象,并为该元素分配它 - 在这种情况下为body。您可以在此处找到示例。不出所料,IE使用不同的机制来做同样的事情,你需要调用 fireEvent 。
If you call document.body.onclick()
, then only the second event will fire and alert "onclick". To get both events to fire, create an event object and dispatch it for the element in question - body in this case. You can find an example here. Unsurprisingly, IE uses a different mechanism to do the same and you need to call fireEvent.
这是现代浏览器的非跨浏览器示例(取自上面的MDC文章),
Here's a non cross-browser example for modern browsers (taken from the MDC article above),
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent('click', true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
document.body.dispatchEvent(clickEvent);
这篇关于如何从QUnit测试中触发本机Javascript事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!