javascript 解决表单仍然提交即使监听处理函数返回false
人气:0复制代码 代码如下:
<form action="//www.qb5200.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="//www.qb5200.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:/https://img.qb5200.com/download-x/developer.mozilla.org/en/DOM/event.preventDefault
2:DOM Events :http://www.w3.org/TR/DOM-Level-2-Events/events.html
加载全部内容