在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>