zoukankan      html  css  js  c++  java
  • jQuery 中的事件冒泡和阻止默认行为

    1、事件冒泡

     1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9     <head>
    10           <script type="text/javascript" src="js/jquery-1.7.2.js"></script>
    11         <script type="text/javascript">
    12             $(function() {
    13                 //为 <span> 元素绑定 click 事件
    14                 $("span").click(function() {
    15                     $("#msg").html($("#msg").html() + "<p>内层span元素被单击</p>");
    16                 });
    17                 //为 Id 为 content 的 <div> 元素绑定 click 事件
    18                 $("#content").click(function() {
    19                     $("#msg").html($("#msg").html() + "<p>外层div元素被单击</p>");
    20                 });
    21                 //为 <body> 元素绑定 click 事件
    22                 $("body").click(function() {
    23                     $("#msg").html($("#msg").html() + "<p>body元素被单击</p>");
    24                 });
    25             });
    26         </script>      
    27         
    28         <!-- CSS -->
    29         <style type="text/css">
    30             #content {
    31                 background: #b17af5;
    32             }        
    33         </style>
    34       </head>
    35   
    36       <!-- HTML -->
    37       <body>
    38           <div id="content">
    39               外层div元素<br />
    40               <span style="background: silver;">内层span元素</span><br />
    41               外层div元素
    42           </div><br />
    43           <div id="msg"></div>
    44       </body>
    45 </html>

    当点击内部 <span> 元素时,会触发自身及外层 <div> 和 <body> 的点击事件,这就是事件冒泡引起的。事件会随着 DOM 的层次结构依次向上传播。

    事件冒泡可能会引起意料之外的效果,有时候需要阻止事件的冒泡行为,使用 stopPropagation() 方法来实现。
    修改 <span> 元素的 click 事件函数:

    1 //为 <span> 元素绑定 click 事件
    2 $("span").click(function(event) {    //为方法添加一个事件对象参数
    3     $("#msg").html($("#msg").html() + "<p>内层span元素被单击</p>");
    4     event.stopPropagation();    //阻止 <span> 的 click 事件冒泡
    5 });

    此时点击内部 <span> 元素时,只会触发自身的 click 事件,不会再向上冒泡。

  • 相关阅读:
    管道命令'|' 和xargs find命令找到后把所有找到的删除
    UVa
    【手势交互】9. PS Move
    jquery时间格式化插件
    Android学习路线(十三)Activity生命周期——暂停和恢复(Pausing and Resuming )一个Activity
    hdu 2604 Queuing (矩阵高速幂)
    【Linux驱动】TQ2440 DM9000E网卡驱动移植(Linux-2.6.30.4)
    bzoj2648 SJY摆棋子
    Hive编程指南_学习笔记01
    通信协议中的转义符
  • 原文地址:https://www.cnblogs.com/PiaoMiaoGongZi/p/4670610.html
Copyright © 2011-2022 走看看