⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙

代码-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>
posted @ 2018-10-18 01:53  羊驼可以吃吗  阅读(380)  评论(0编辑  收藏  举报
⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙ ⊙︿⊙