zoukankan      html  css  js  c++  java
  • 0171 事件对象 之 阻止默认行为:preventDefault(),returnValue,return false

    html中一些标签有默认行为,例如a标签被单击后,默认会进行页面跳转。

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
    
        </style>
    </head>
    
    <body>
        <div>123</div>
        <a href="http://www.baidu.com">百度</a>
        <form action="http://www.baidu.com">
            <input type="submit" value="提交" name="sub">
        </form>
    
        <script>
            // 常见事件对象的属性和方法
            // 1. 返回事件类型
            var div = document.querySelector('div');
            div.addEventListener('click', fn);
            div.addEventListener('mouseover', fn);
            div.addEventListener('mouseout', fn);
    
            function fn(e) {
                console.log(e.type);
            }
    
            // 2. 阻止默认行为(事件) 让链接不跳转 或者让提交按钮不提交
            var a = document.querySelector('a');
            a.addEventListener('click', function(e) {
                e.preventDefault(); //  dom 标准写法
            })
    
            // 3. 传统的注册方式
            a.onclick = function(e) {
                // 普通浏览器 e.preventDefault();  方法
                // e.preventDefault();
                // 低版本浏览器 ie678  returnValue  属性
                // e.returnValue;
                // 我们可以利用return false 也能阻止默认行为 没有兼容性问题 特点: return 后面的代码不执行了, 而且只限于传统的注册方式
                return false; // 必须写false,不写false,一样会跳转到
                alert(11);
            }
        </script>
    </body>
    
    </html>
    
  • 相关阅读:
    3组Alpha冲刺5/6
    3组Beta冲刺4/5
    3组Alpha冲刺6/6
    3组Beta冲刺2/5
    3组Beta冲刺3/5
    delegate Demo (一个关于System.Timers.Timer的Demo)
    System.Web.HttpException 与 HTTP Error 404.13 Not Found问题解决说明
    常用SQL关于表的操作
    设计模式学习笔记:单例模式
    JS 实践杂记
  • 原文地址:https://www.cnblogs.com/jianjie/p/12176943.html
Copyright © 2011-2022 走看看