DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript 解決表單仍然提交即使監聽處理函數返回false
javascript 解決表單仍然提交即使監聽處理函數返回false
編輯:關於JavaScript     

復制代碼 代碼如下:
<form action="http://www.jb51.net" id="form">
<input type="text" />
<input type="submit" />
</form>
<script>
var code = function () {
return false;
};
var element = window.document.getElementById("form");
if (element.addEventListener) {
element.addEventListener("submit", code, false);
}
</script>

修改後的Code:
復制代碼 代碼如下:
<form action="http://www.jb51.net" id="form">
<input type="text" />
<input type="submit" id="btnSubmit" name="btnSubmit" value="Submit" />
</form>
<script>
var code = function (eventObject) {
if (eventObject.preventDefault) {
eventObject.preventDefault();
} else if (window.event) /* for ie */ {
window.event.returnValue = false;
}
return true;
};
window.onload = function(){
var element = window.document.getElementById("form");
if (element.addEventListener) {
element.addEventListener("submit", code, false);
} else if (element.attachEvent) {
element.attachEvent("onsubmit", code);
}
}
</script>

備注:

1:preventDefault函數的使用請參考 https://developer.mozilla.org/en/DOM/event.preventDefault
2:DOM Events :http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-preventDefault

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved