理解jquery事件冒泡,jquery事件冒泡

來源:互聯網
上載者:User

理解jquery事件冒泡,jquery事件冒泡

一、什麼是jquery事件冒泡
在很多教材或者手冊都可能會涉及到事件冒泡的概念,老手來說這當然是最基本的概念,但往往對於初學者可能比較陌生或者說從來沒有聽說過。下面就結合代碼執行個體來簡單介紹一下什麼是事件冒泡。
代碼執行個體如下:

<html><head><meta charset=" gb2312"><title>事件冒泡</title><script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script><script type="text/javascript">$(document).ready(function(){ $("#second").click(function(){  alert("我是second");     }) $("#first").click(function(){  alert("我是first");     })})</script></head><body><p id="first"><a id="second" href="http://www.baidu.com">點擊查看效果</a></p></body></html>

在以上代碼中,我們可能只想點擊錨點後彈出“我是third”,但是令人奇怪的事情卻是所有父元素定義的click事件都會被觸發。這就是一個典型的事件冒泡效果。所謂的冒泡事件就是,如果在某一個對象上觸發某一類事件(如上例的click事件),那麼此事件會向對象的父級對象傳播,並觸發父物件上定義的同類事件。事件傳播的方向是從最底層到最頂層,類似於水泡從水底浮上來一般。
二、javascript如何阻止事件冒泡
冒泡事件能夠帶來便利,有時候也會帶來麻煩,下面就簡單介紹一下如何阻止事件冒泡。
代碼執行個體如下:

<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <head><title>事件冒泡</title><style type="text/css">#grandfather{ border:1px solid #0066FF; cellpadding:0px; cellspacing:0px;}#grandfather td{ border: 1px solid #0066FF;}</style><script type="text/javascript">function trclick(){ alert("父親的onclick事件觸發");}function tableclick(){ alert("祖父的onclick事件觸發");}window.onload=function(){ var grandfather=document.getElementById("grandfather"); var father=document.getElementById("father"); var noStop=document.getElementById("noStop"); var haveStop=document.getElementById("haveStop");  grandfather.onclick=tableclick; father.onclick=trclick;  noStop.onclick=function(){ alert("沒有阻止冒泡的子項目"); } haveStop.onclick=function(evt){ alert("阻止冒泡的子項目"); if(window.event){ event.cancelBubble=true; } else if(evt){ evt.stopPropagation(); } }}</script></head><body><table width="204" id="grandfather"> <tr > <td width="96"></td> <td width="96"></td> </tr> <tr id="father"> <td id="noStop">沒有阻止事件冒泡</td> <td id="haveStop">阻止了事件冒泡</td> </tr> <tr> <td> </td> <td> </td> </tr></table></body></html>

代碼注釋:
1.if(window.event)這個用來相容IE8和IE8一下瀏覽器。
2. evt.stopPropagation()這個是標準瀏覽器。

以上代碼中,一個儲存格阻止了事件冒泡,一個沒有阻止事件冒泡,希望對大家的學習有所協助。

您可能感興趣的文章:
  • Jquery阻止事件冒泡 event.stopPropagation
  • jquery 事件冒泡的介紹以及如何阻止事件冒泡
  • 事件冒泡是什麼如何用jquery阻止事件冒泡
  • jQuery阻止事件冒泡具體實現
  • js阻止冒泡及jquery阻止事件冒泡樣本介紹
  • JQuery中阻止事件冒泡幾種方式及其區別介紹
  • jQuery中事件對象e的事件冒泡用法樣本介紹
  • JavaScript和JQuery的滑鼠mouse事件冒泡處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.