取消事件冒泡(多个事件重复发生)

来源:互联网 发布:2016淘宝联盟导购推广 编辑:程序博客网 时间:2024/05/15 08:26

 在默认情况下,发生在一个子元素上的单击事件(或者其他事件),如果在其父级元素绑定了一个同样的事件,此时点击子元素,click事件会首先被子元素捕获,执行绑定的事件程序,之后会被父级元素捕获,再次激发一段脚本的执行,这就是所谓的“事件冒泡”。

 

 

 

在通常情况下,我们只希望事件发生在它的目标而并非它的父级元素上,只需加个stopBubble方法,即可取消事件冒泡,见下:

 

 

现在你可能想知道,什么时候需要阻止事件冒泡?事实上,现在绝大多数情况下都可以不必在意它。但是当你开始开发动态应用程序(尤其是需要处理键盘和鼠标)的时候,就有这个必要了。

 

 

英文参考:

 

cancelBubble Property



Sets or retrieves whether the current event should bubble up the hierarchy of event handlers.

Syntax

event.cancelBubble [ = bCancel ]

Possible Values

bCancelBoolean that specifies or receives one of the following values.falseDefault. Bubbling is enabled, allowing the next event handler in the hierarchy to receive the event. trueBubbling is disabled for this event, preventing the next event handler in the hierarchy from receiving the event.

The property is read/write. The property has a default value of false.

Expressions can be used in place of the preceding value(s), as of Microsoft® Internet Explorer 5. For more information, see About Dynamic Properties.

Remarks

Using this property to cancel bubbling for an event does not affect subsequent events.

Example

This example cancels bubbling of the onclick event if it occurs in the img object when the user presses the SHIFT key. This prevents the event from bubbling up to the onclick event handler for the document.

 

 

Standards Information

There is no public standard that applies to this property.

原创粉丝点击