原生javascript的return false並不能阻止事件冒泡

antzone發表於2017-04-13

一個需要特別注意的問題是,儘管jQuery的return false能夠阻止事件冒泡。

但是原生的javascript的return false並不具備此能力。

先來看一段jQuery的程式碼例項:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
a {
  text-decoration: none;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
window.onload=function(){
  $("#mytest").click(function () {
    alert("我是子元素")
    return false
  })
  $("#parent").click(function () {
    alert("我是父元素")
  })
}
  </script>
</head>
<body>
<div id="parent">
  <div style="text-align:center">
    <a href="#" id="mytest">點選彈出提示</a>
  </div>
</div>
</body>
</html>

上面的程式碼使用return false可以阻止事件冒泡,但是改成原生javascript就不能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
a {
  text-decoration: none;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
window.onload=function(){
  document.getElementById("mytest").onclick=function(){
    alert("我是子元素");
    return false
  }
  document.getElementById("parent").onclick=function(){
    alert("我是父元素");
  }
}
  </script>
</head>
<body>
<div id="parent">
  <div style="text-align:center">
    <a href="#" id="mytest">點選彈出提示</a>
  </div>
</div>
</body>
</html>

上面的程式碼則無法阻止事件冒泡現象,所以大家不要弄混亂了。

相關文章