Mouse click vs jquery click vs dispatchEvent click

旧城冷巷雨未停 提交于 2019-12-10 15:06:58

问题


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.net/5uvjwa4t/2/

Thanks


回答1:


The 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});


来源:https://stackoverflow.com/questions/32010675/mouse-click-vs-jquery-click-vs-dispatchevent-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!