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

作者:马温柔 时间:2023-09-10 08:57:36 


<%@ 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" href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" mce_href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" onclick="alert('我是最里层!')">点击我</a>
</div>
</div>
</form>
</body>
</html>

比如上面这个页面,

分为三层:divOne是第外层,divTwo中间层,hr_three是最里层;

他们都有各自的click事件,最里层a标签还有href属性。

运行页面,点击“点击我”,会依次弹出:我是最里层---->我是中间层---->我是最外层

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

这就是事件冒泡,本来我只点击ID为hr_three的标签,但是确执行了三个alert操作。

事件冒泡过程(以标签ID表示):hr_three----> divTwo----> divOne 。从最里层冒泡到最外层。

如何来阻止?

1.event.stopPropagation();


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

再点击“点击我”,会弹出:我是最里层,然后链接到百度

2.return false;

如果头部加入的是以下代码


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

再点击“点击我”,会弹出:我是最里层,但不会执行链接到百度页面

由此可以看出:

1.event.stopPropagation();

事件处理过程中,阻止了事件冒泡,但不会阻击默认行为(它就执行了超链接的跳转)

2.return false;

事件处理过程中,阻止了事件冒泡,也阻止了默认行为(比如刚才它就没有执行超链接的跳转)

还有一种有冒泡有关的:

3.event.preventDefault();

如果把它放在头部A标签的click事件中,点击“点击我”。

会发现它依次弹出:我是最里层---->我是中间层---->我是最外层,但最后却没有跳转到百度

它的作用是:事件处理过程中,不阻击事件冒泡,但阻击默认行为(它只执行所有弹框,却没有执行超链接跳转)

来源:https://www.cnblogs.com/angel648/p/11409799.html

标签:JS,事件冒泡
0
投稿

猜你喜欢

  • 利用python发送和接收邮件

    2022-01-23 10:22:07
  • SQL Server数据库连接中常见的错误分析

    2009-01-15 12:51:00
  • Perl哈希表用法解析

    2023-08-23 19:12:48
  • Python日志处理模块logging用法解析

    2021-01-05 14:45:55
  • javascript实现rgb颜色转换成16进制格式

    2024-04-18 09:33:58
  • Go语言基于HTTP的内存缓存服务的实现

    2024-05-21 10:25:12
  • matplotlib之属性组合包(cycler)的使用

    2021-04-16 19:31:04
  • python将txt等文件中的数据读为numpy数组的方法

    2022-04-20 14:08:10
  • Python3之乱码\\xe6\\x97\\xa0\\xe6\\xb3\\x95处理方式

    2021-03-30 10:19:47
  • delete from 表名与truncate table 表名区别

    2012-11-30 20:31:37
  • Python画图练习案例分享

    2021-06-25 14:48:07
  • Python基础之函数与控制语句

    2021-02-02 16:22:49
  • Python中的zipfile模块使用详解

    2023-02-26 22:44:37
  • Python计算矩阵的和积的实例详解

    2021-06-06 10:09:34
  • mysql installer community 8.0.12.0安装图文教程

    2024-01-15 05:16:33
  • 天极产品设计流程

    2007-10-11 18:47:00
  • 在VS Code上搭建Python开发环境的方法

    2021-02-19 14:20:38
  • MYSQL Binlog恢复误删数据库详解

    2024-01-27 06:17:30
  • Python免费验证码识别之ddddocr识别OCR自动库实现

    2023-02-25 12:28:31
  • Python中的数据可视化matplotlib与绘图库模块

    2021-08-09 06:02:09
  • asp之家 网络编程 m.aspxhome.com