jQuery事件冒泡和默认行为

在jQuery的事件冒泡和默认行为中,需要掌握四样东西。希望下面的代码会对大家有所帮助。在控制台中一段一段的查看运行效果。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery事件冒泡和默认行为</title>
    <style>
    *{
        margin: 0;
        padding: 0
    }
    .father{
        width: 200px;
        height: 200px;
        background: red
    }
    .son{
        width: 100px;
        height: 100px;
        background: blue;
    }
    </style>
    <script src="js/jquery.js"></script>
   	<script>
   		$(function(){
               /*
               1.什么是事件冒泡
               2.如何阻止事件冒泡(两种方式,如下)
               3.什么是默认行为?
               4.如何阻止默认行为(两种方式,如下)
               */
            /*
           $(".son").click(function(event){
               alert("son");//默认会执行father的方法

               //return false;//当点击".son"后,不会再执行father的方法
               event.stopPropagation();
           });
           $(".father").click(function(){
               alert("father");
           });
           */

           $("a").click(function(event){
               alert("弹出注册框");

               //return false;//在页面中点完确定后不会继续跳转
               event.preventDefault();
           })
        })
   	</script>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <a href="http://www.baidu.com">注册</a><!--点击完后 默认会跳转-->
    <form action="http://www.taobao.com"><!--点击完后 默认会跳转-->
        <input type="text">
        <input type="submit">
</form>
</body>
</html>

若有任何疑问或是不解,请在下方评论留言,谢谢。

猜你喜欢

转载自blog.csdn.net/YYxiaobao0726/article/details/88204783
今日推荐