admin管理员组文章数量:1336659
Can someone explain to me why actual mouse click and $('div').click() runs click event 3 times while $('div')[0].dispatchEvent(new MouseEvent('click')) runs click event only 1 time according to browser console?
Here's a simple html code:
<div>test</div>
Here's a javascript code:
$('*').click(function(e){
console.log(e);
});
var c = new MouseEvent('click');
// Actual mouse click output event 3 times
//$('div').click(); // output event 3 times
$('div')[0].dispatchEvent(c); // output event 1 time
/
Thanks
Can someone explain to me why actual mouse click and $('div').click() runs click event 3 times while $('div')[0].dispatchEvent(new MouseEvent('click')) runs click event only 1 time according to browser console?
Here's a simple html code:
<div>test</div>
Here's a javascript code:
$('*').click(function(e){
console.log(e);
});
var c = new MouseEvent('click');
// Actual mouse click output event 3 times
//$('div').click(); // output event 3 times
$('div')[0].dispatchEvent(c); // output event 1 time
http://jsfiddle/5uvjwa4t/2/
Thanks
Share Improve this question edited Aug 14, 2015 at 16:47 diurii asked Aug 14, 2015 at 12:56 diuriidiurii 631 silver badge6 bronze badges 1-
1
Because in
dispatchEvent
you specified adiv
and inclick
you select all using*
(including html & body) tags + div. – Zakaria Acharki Commented Aug 14, 2015 at 13:06
1 Answer
Reset to default 7The asterisk matches the <html>
and <body
tags as well, and as click events bubble it's fired on three elements when you use the asterisk as a selector for the event handler.
$('*') // matches all elements, including html and body
$('div') // matches the DIV only
When you fire a click on a div that is nested like this
<html>
<body>
<div>
The click travels up (bubbles) and fires on all parent elements as well.
Using dispatchEvent
fires the event three times for me in Chrome, but there could be differences in other browsers.
To make it consistently bubble the bubbles
setting can be set, that way it will behave as a regular click and bubble up.
var c = new MouseEvent('click', {bubbles:true});
本文标签: javascriptMouse click vs jquery click vs dispatchEvent clickStack Overflow
版权声明:本文标题:javascript - Mouse click vs jquery click vs dispatchEvent click - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742420374a2471536.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论