18.阻止默认操作e.preventDefault();防止冒泡事件:e.stopPropagation()

 

一、加了e.preventDefault();会阻止a标签默认的点击跳转效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
            $("a").on("click", function (e) {
                e.preventDefault();
            })
        })
    </script>
</head>
<body>
<a href="http://www.cqmu.edu.cn">重庆医科大学</a>
</body>
</html>

二、加event.stopPropagation()防止冒泡事件;

    <script src="jquery/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("input[type=button]").bind("click",function (event) {
                event.stopPropagation();
                alert("a");
            })
            $("div").bind("click",function (event) {
                // event.stopPropagation();
                alert("b");
            })
        })
    </script>
</head>
<body>
<div style="position: absolute;top: 100px;left: 100px;background-color: red;">
    <input type="button" value="按钮">
</div>

 三、如果想要事项既要阻止默认事件又要防止冒泡,那可以直接写两个,不过还有一个更简洁的方法,就是直接写return false;

如:

$("a").bind("click",function(e){
   return false; 
})

原文地址:https://www.cnblogs.com/alex-xxc/p/9738803.html