取消事件:2种情况:
1. 在html中绑定事件处理函数:2个return
<span style="font-size:14px;"><script type="text/javascript">
function validate(obj) {
if (confirm("提交表单?")) {
alert(obj.value);
return true;
} else {
alert(obj.value);
return false;
}
}
</script>
<body>
<form action="http://www.baidu.com" <span style="background-color: rgb(255, 255, 153);">οnsubmit="return validate(document.getElementByIdx_x('myText'))</span>;"> <!—参数的这种写法注意下-->
<input type="text" id="myText"/>
<input type="submit" value="submit"/>
</form>
</body></span>
2. js中动态绑定事件处理函数:
DOM标准:e.preventDefault()
IE8: e.returnValue=false
兼容:if(e.preventDefault){
e.preventDefault()
}else{
e.returnValue=false
}
<span style="font-size:14px;"><html>
<head>
<title>表单提交的方式</title>
<script>
function checkUser() {
//事件触发时,获取事件对象
var e=window.event||arguments[0]
var result = document.getElementById("userid").value;
var password = document.getElementById("userpassid").value;</span>
<span style="font-size:14px;"> //当用户名或密码为空,取消事件,阻止表单提交
if(reuslt==""||password==""){
<span style="background-color: rgb(255, 255, 102);"> if(e.preventDefault()){
e.preventDefault();
}else{
e.returnValue=false;
}</span>
}
}
window.onload = function () {
//js动态绑定事件
<span style="color:#ffff99;">do</span><span style="background-color: rgb(255, 255, 153);">cument.forms("myform").addEventListener("submit","checkUser",false);</span>
}
</script>
</head>
<body>
<form id="formid" name="myform" method='post' action='user_login_submit.action'>
<table width="100%" border="0">
<tr>
<td width="60" height="40" align="right">用户名 </td>
<td><input type="text" value="" class="text2" name="username" id="userid"/></td>
</tr>
<tr>
<td width="60" height="40" align="right">密 码 </td>
<td><input type="password" value="" class="text2" name="userpass" id="userpassid"/></td>
</tr>
<tr>
<td width="60" height="40" align="right"> </td>
<td>
<div class="c4">
<input type="submit" value="" class="btn2"/>
</div>
</td>
</tr>
</table>
</form>
</body>
</html></span>
来源:CSDN
作者:yuanmei1986
链接:https://blog.csdn.net/yuanmei1986/article/details/50779192