程序员人生 网站导航

JS解决表单依旧提交即使监听处理函数返回false

栏目:jscript时间:2013-11-18 15:32:33

如何解决表单依旧提交即使监听处理函数返回false

代码
<form action="http://www.example.com" 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.example.com" 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

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐