阻止事件冒泡 和 阻止事件默認行爲

1.event.stopPropagation()方法 這是阻止事件的冒泡方法,不讓事件向documen上蔓延,可是默認事件任然會執行,當你掉用這個方法的時候,若是點擊一個鏈接,這個鏈接仍然會被打開,css

2.event.preventDefault()方法 這是阻止默認事件的方法,調用此方法是,鏈接不會被打開,可是會發生冒泡,冒泡會傳遞到上一層的父元素;html

3.return false  ; 這個方法比較暴力,他會同事阻止事件冒泡也會阻止默認事件;寫上此代碼,鏈接不會被打開,事件也不會傳遞到上一層的父元素;能夠理解爲return false就等於同時調用了event.stopPropagation()和event.preventDefault()jquery

 

4.咱們來看看幾組demo,使用jquery進行DOM操做 這是html代碼,div裏面套了一個a標籤,鏈接到百度htm

 

css代碼,a標籤佔父元素的空間的1/4,背景顏色爲紅色; .box1{ height: 200px; width: 600px; margin: 0 auto; } .box1 a{ display: block; height: 50%; width: 50%; background:red; } 下面來看js代碼,事件

第一種  //不阻止事件冒泡和默認事件 $(".box1").click(function(){ console.log("1")//不阻止事件冒泡會打印1,頁面跳轉; });io

 

第二種 //阻止冒泡 $(".box1 a").click(function(event){ event.stopPropagation();//不會打印1,可是頁面會跳轉; }); $(".box1").click(function(){ console.log("1") });console

 

第三種 $(".box1 a").click(function(event){ //阻止默認事件 event.preventDefault();//頁面不會跳轉,可是會打印出1, }); $(".box1").click(function(){ console.log("1"); });event

 

第四種 $(".box1").click(function(){ console.log("1") }); //阻止冒泡 $(".box1 a").click(function(event){ event.stopPropagation(); //阻止默認事件 event.preventDefault() //頁面不會跳轉,也不會打印出1 })function

 

第五種 $(".box1").click(function(){ console.log("1") }); $(".box1 a").click(function(event){ return false; //頁面不會跳轉,也不會打印出1,等於同時調用了event.stopPropagation()和event.preventDefault()class