欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS阻止事件冒泡的方法詳解

 更新時(shí)間:2019年08月26日 08:15:14   作者:馬溫柔  
在本篇文章里小編給大家整理的是關(guān)于JS如何阻止事件冒泡的相關(guān)知識(shí)點(diǎn)內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs"Inherits="Default5"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Porschev---Jquery 事件冒泡</title>

<script src="jquery-1.3.2-vsdoc.js" type="text/javascript"></script>

</head>
<body>
  <form id="form1" runat="server">
    <div id="divOne" onclick="alert('我是最外層');">
      <div id="divTwo" onclick="alert('我是中間層!')">
        <a id="hr_three"  rel="external nofollow" rel="external nofollow" mce_ rel="external nofollow" rel="external nofollow" onclick="alert('我是最里層!')">點(diǎn)擊我</a>
      </div>
    </div>
  </form>
</body>
</html>

比如上面這個(gè)頁面,

分為三層:divOne是第外層,divTwo中間層,hr_three是最里層;

他們都有各自的click事件,最里層a標(biāo)簽還有href屬性。

運(yùn)行頁面,點(diǎn)擊“點(diǎn)擊我”,會(huì)依次彈出:我是最里層---->我是中間層---->我是最外層

---->然后再鏈接到百度.

這就是事件冒泡,本來我只點(diǎn)擊ID為hr_three的標(biāo)簽,但是確執(zhí)行了三個(gè)alert操作。

事件冒泡過程(以標(biāo)簽ID表示):hr_three----> divTwo----> divOne 。從最里層冒泡到最外層。

如何來阻止?

1.event.stopPropagation();

<script type="text/javascript">
    $(function() {
      $("#hr_three").click(function(event) {
        event.stopPropagation();
      });
    });
<script>

再點(diǎn)擊“點(diǎn)擊我”,會(huì)彈出:我是最里層,然后鏈接到百度

2.return false;

如果頭部加入的是以下代碼

<script type="text/javascript">
$(function() {
  $("#hr_three").click(function(event) {
    return false;
  });
});
<script>

再點(diǎn)擊“點(diǎn)擊我”,會(huì)彈出:我是最里層,但不會(huì)執(zhí)行鏈接到百度頁面

由此可以看出:

1.event.stopPropagation();

事件處理過程中,阻止了事件冒泡,但不會(huì)阻擊默認(rèn)行為(它就執(zhí)行了超鏈接的跳轉(zhuǎn))

2.return false;

事件處理過程中,阻止了事件冒泡,也阻止了默認(rèn)行為(比如剛才它就沒有執(zhí)行超鏈接的跳轉(zhuǎn))

還有一種有冒泡有關(guān)的:

3.event.preventDefault();

如果把它放在頭部A標(biāo)簽的click事件中,點(diǎn)擊“點(diǎn)擊我”。

會(huì)發(fā)現(xiàn)它依次彈出:我是最里層---->我是中間層---->我是最外層,但最后卻沒有跳轉(zhuǎn)到百度

它的作用是:事件處理過程中,不阻擊事件冒泡,但阻擊默認(rèn)行為(它只執(zhí)行所有彈框,卻沒有執(zhí)行超鏈接跳轉(zhuǎn))

以上就是本次介紹的全部知識(shí)點(diǎn)內(nèi)容,感謝大家對腳本之家的支持。

相關(guān)文章

最新評論