恶补jquery(四)jquery中事件

事件

当我们在打开一个页面的时候,浏览器会对页面进行解释执行,这实际上是通过执行事件来驱动的,在页面加载事件时,执行Load()事件,是这个事件实现浏览器解释执行代码的过程。

事件机制事件中的冒泡现象

冒泡现象说的是事件执行顺序,,当一个对象上触发了一个事件,如果没有定义此事件的处理程序或者事件返回true,那么这个事件就会向这个对象的父级对象传播,从里到外,直到他被处理(父级对象所有同类事件都被激活),或者它到达了对象层次的顶层(即document对象)。

通俗的讲:假把设一杯水分成不同颜色的几层,加热水的时候,当底层中有一个气泡出现时,气泡会一层层的上升,直到最层顶部。而我们不管在哪一层观察都能捕捉到这个气泡,这杯水就是我们的”DOM“,”气泡“就是我们的事情气泡。

事件冒泡示例

如下代码所示

<span style="font-size:14px;"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""><html xmlns=""><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JavaScript</title><style type="text/css">#box {width:200px; height:100px; border:2px solid blue}#box h5 {margin:0; padding:2px 5px; font-size:18px; text-align:right; background:blue; cursor:move}#box h5 a {text-decoration:none; color:#FFF}</style></head><body><div id="box"><h5 onclick="startDrag();"><a onclick="closeBox();" href="javascript:void(0);">close</a></h5><div id="testInfo"></div></div><script type="text/javascript">function startDrag(){document.getElementById('testInfo').innerHTML += 'startDrag<br/>';}function closeBox(){document.getElementById('testInfo').innerHTML += 'closeBox<br/>';}</script></body></html></span> 运行结果如图1:

图1

由此我们可以看到,对于同一事件来说(都是onclick事件),先是底层触发,再是上一层触发事件,也就是”从里向外冒泡“。

图2

那如何阻止冒泡?

js阻止冒泡现象

如下代码所示:

<span style="font-size:14px;"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""><html xmlns=""><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JavaScript</title><style type="text/css">#box {width:200px; height:100px; border:2px solid blue}#box h5 {margin:0; padding:2px 5px; font-size:18px; text-align:right; background:blue; cursor:move}#box h5 a {text-decoration:none; color:#FFF}</style></head><body><div id="box"><h5 onclick="startDrag();"><a onclick="closeBox();" href="">close</a></h5><div id="testInfo"></div></div><script type="text/javascript">function startDrag(){document.getElementById('testInfo').innerHTML += 'startDrag<br/>';}function closeBox(e){document.getElementById('testInfo').innerHTML += 'closeBox<br/>';stopPropagation(e);}function stopPropagation(e) {e = e || window.event;if(e.stopPropagation) { //W3C阻止冒泡方法e.stopPropagation();} else {e.cancelBubble = true; //IE阻止冒泡方法} } </script></body></html></span>jquery阻止冒泡现象

如果是通过jquery访问的话,阻止冒泡现象方法如下

<span style="font-size:14px;"> $(function() {$("a").click(function(event) {return false;}); });</span> 或者<span style="font-size:14px;">$(function() {$("a").click(function(event) {event.stopPropagation();}); });</span>旁观者的姓名永远爬不到比赛的计分板上。

恶补jquery(四)jquery中事件

相关文章:

你感兴趣的文章:

标签云: