使用 event.preventDefault 攔截表單的提交


event.preventDefault() 方法 W3C 官方的定義是:取消事件的默認動作,不單單可以攔截表單的提交,<a>標簽的跳轉,

<input>標簽的輸入等等默認動作都會被阻止動作或者輸入.

但是IE瀏覽器對event.preventDefault()不支持!

解決方式:

	function stopDefault(e){
		if(e && e.preventDefault){
			e.preventDefault();
		}else{
			window.event.returnValue = false;
		}
	}

表單如下:

一:普通的onsubmit 攔截表單

        <form action="" name="asd" onsubmit=”return check_method_1()”>
			<input type="text" name="a">
			<input type="submit" name="submit" value="提交">
		</form>

二:使用event.preventDefault()攔截表表單

        <form action="" name="dsa" method="post">
			<input type="text" name="a">
			<input type="submit" id="event" value="提交" onclick="check_method_2(event)">
		</form>
 
	function check_method_2(event){
		e = e || window.event;
		if($("form[name='a'] input").val() == ''){
			alert('請輸入用戶名');
			if(document.all) e.returnValue = false;	//IE,window.event.returnValue = false 阻止元素默認行為
			else e.preventDefault();//Chrome,oprea,firefox event.preventDefault() 阻止元素默認行為
		}
	}
也可以這樣寫:
	$("#event").bind({
		click:function(check){
			if(!checkAll()){
				stopDefault(check);return;//stopDefault來自兼容性處理
			}
		}
	})
表單一和表單二中的攔截都可以寫對應的攔截方法,當所有方法返回真實 遞交表單,否則阻止。
	function checkAll(){
		if(check_a() && check_b() && check_c(){
			return true;
		}else{
			return false;
		}
	}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM