zoukankan      html  css  js  c++  java
  • 代码-JS之阻止默认行为

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
    
    <form name="f1" action="test.html" method="post">
        用户名:<input type="text" name="username"><span style="color:red;">用户名必填</span><br>
        <input type="submit" value="提交">
    </form>
    
    <script>
        /*********** 阻止表单提交二 ************/
        //定义一个兼容的阻止标签默认行为的方法
        function zuzhi(e) {
            //标准浏览器:evt.preventDefault();
            //IE内核浏览器:window.event.returnValue = false;
            if(e.preventDefault){
                e.preventDefault();
            }else{
                e.returnValue = false;
            }
        }
        //获取表单的DOM对象
        var f1 = document.f1; // 遗留DOM方式
        //为表单绑定提交事件
        f1.onsubmit = function(evt){
            if(this.username.value == ''){
                alert('用户名不能为空');
                //阻止表单提交
                var e = window.event||evt;
                zuzhi(e);
            }
        };
    
        /*********** 阻止表单提交二 ************/
        document.querySelector('input[type="submit"]').onclick = function (evt) {
            if(document.f1.username.value == ''){
                alert('用户名不能为空');
                return false; //阻止表单提交
            }
        };
    </script>
    
        <!--/*********** 阻止表单提交三 ************/-->
    <a href="test.html" onclick="return confirm('你确定要提交吗');">跳转</a>
    
    </body>
    </html>
    
    Copyright [2018] by [羊驼可以吃吗] form [https://www.cnblogs.com/phpisfirst/]
  • 相关阅读:
    C语言运算符优先级和口诀
    跨域问题的解决方案 php
    浅谈跨域攻击及预防
    浅析Websocket--PHP
    linux下的删除目录和文件的方法
    python魔法方法
    双指针
    python常用模块
    python三大器
    对闭包的误区
  • 原文地址:https://www.cnblogs.com/phpisfirst/p/9819141.html
Copyright © 2011-2022 走看看