日期:2014-05-16  浏览次数:20363 次

js 阻止子元素事件 冒泡 到 父元素
场景:
一个父元素内部有个子元素,父与子元素都绑定一个click事件,此时,点击子元素后,也会触发父元素的事件,即“事件冒泡”,如何阻止呢?

<div id="parent" style="width:300px;height:300px;background:red;padding:50px"><div id="children" style="width:200px;height:200px;background:white;"></div></div>

<script>
  var $ = function(id){
       return document.getElementById(id);
  }
  $('parent').onclick=function(){
     alert(1);
  };
  $('children').onclick=function(e){
     alert(2);
	 //1.js 阻止事件冒泡到父元素
	 if (e.stopPropagation){ e.stopPropagation();}
  	 else {e.cancelBubble = true;}
	 //2.如果是用jQuery Lib来绑定事件则 return false;即可
	 //return false;
  };
</script>