取消事件: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>