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?
有人能解释一下为什么实际的鼠标点击和$('div').click()运行点击事件3次而$('div')[0]。dispatchEvent(新的MouseEvent('click'))根据浏览器控制台只运行一次click event ?
Here's a simple html code:
这里有一个简单的html代码:
<div>test</div>
Here's a javascript code:
这里有一个javascript代码:
$('*').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/
http://jsfiddle.net/5uvjwa4t/2/
Thanks
谢谢
1 个解决方案
#1
5
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
当你点击这样嵌套的div时
<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.
使用dispatchEvent在Chrome中为我触发三次事件,但在其他浏览器中可能存在差异。为了使它始终保持气泡,可以设置气泡设置,这样它就会像普通的点击和气泡一样。
var c = new MouseEvent('click', {bubbles:true});
#1
5
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
当你点击这样嵌套的div时
<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.
使用dispatchEvent在Chrome中为我触发三次事件,但在其他浏览器中可能存在差异。为了使它始终保持气泡,可以设置气泡设置,这样它就会像普通的点击和气泡一样。
var c = new MouseEvent('click', {bubbles:true});