鼠标点击vs jquery点击vs dispatchEvent点击 [英] Mouse click vs jquery click vs dispatchEvent click

查看:1590
本文介绍了鼠标点击vs jquery点击vs dispatchEvent点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释为什么实际的鼠标点击
$('div')。 $('div')[0] .dispatchEvent(new MouseEvent('click'))根据浏览器控制台只运行一次click事件



这里有一个简单的html代码:

 < div> test< / div> 

以下是一段javascript代码:

  $('*')click(function(e){
console.log(e);
});

var c = new MouseEvent('click');

//实际的鼠标点击输出事件3次
// $('div')。 // output event 3次
$('div')[0] .dispatchEvent(c); // output event 1 time

http://jsfiddle.net/5uvjwa4t/2/



感谢

解决方案

星号符合< html> < body 标签,以及当您使用星号作为事件处理程序的选择器时,点击事件气泡对三个元素触发。

  $('*')//匹配所有元素,包括html和body 

$('div')//仅匹配DIV



当您点击嵌套的div时,会出现

 < html> 
< body>
< div>

点击向上移动(气泡),并在所有父元素上触发。



使用 dispatchEvent 在Chrome中为我三次触发事件,但在其他浏览器中可能会有差异。

为了使其始终发泡,可以设置气泡设置,这样它将作为常规点击和冒泡起来。

  var c = new MouseEvent('click',{bubbles:true}); 


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

解决方案

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

这篇关于鼠标点击vs jquery点击vs dispatchEvent点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆