1. 程式人生 > >關於jQuery中button標籤自動提交form表單的問題

關於jQuery中button標籤自動提交form表單的問題

在form表單中,當我們將button標籤作為事件源,使用jQuery對其繫結一個事件,來造作多選框的同步多選,反選,或者解析輸入文字進而匹配相應選項設定時會發現,在點選button之後,結果會出現,但卻一閃而過.這是為什麼嘛呢?

當我們將form表單的"Method" 屬性設定為"get",在位址列或者檢視網頁原始碼(F12--js)我們會發現:form表單被提交了.但我們我們明明並沒有設定任何提交表單事件!

此時我們有兩種解決方法:

1.將button標籤放到表單之外.

2.將button標籤改為 input標籤 ,"type"型別設定為"button".

以下是原始碼

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
</head>
<body>
請輸入城市:<input type="text" id="id"/> 
<br/><br/>
城市複選框:
<div style="width:200px;background:red;">
	<form>
	<input type="checkbox" name="city" value="北京"/>北京
	<input type="checkbox" name="city" value="南京"/>南京
	<input type="checkbox" name="city" value="上海"/>上海
	</form>
</div>
	<br/>
	<button  onclick="checkCity()">判斷</button>
	<!--<input type="button" value="判斷" onclick="checkCity()"/>-->
</body>
<script>
	function checkCity(){
		
		$("div input[type='checkbox']").prop("checked",false);
		var cityValue = $("#id").val();		
		$("div input[value='"+cityValue+"']").prop("checked",true);
	}	
</script>
</html>