Home > Web Front-end > JS Tutorial > javascript solves the problem that the form is still submitted even if the listening handler function returns false_javascript tips

javascript solves the problem that the form is still submitted even if the listening handler function returns false_javascript tips

WBOY
Release: 2016-05-16 18:32:30
Original
978 people have browsed it

复制代码 代码如下:





<script> <br>var code = function () { <br>return false; <br>}; <br>var element = window.document.getElementById("form"); <br>if (element.addEventListener) { <br>element.addEventListener("submit", code, false); <br>} <br></script>

修改后的Code:
复制代码 代码如下:





<script> <br>var code = function (eventObject) { <br>if (eventObject.preventDefault) { <br>eventObject.preventDefault(); <br>} else if (window.event) /* for ie */ { <br>window.event.returnValue = false; <br>} <br>return true; <br>}; <br>window.onload = function(){ <br>var element = window.document.getElementById("form"); <br>if (element.addEventListener) { <br>element.addEventListener("submit", code, false); <br>} else if (element.attachEvent) { <br>element.attachEvent("onsubmit", code); <br>} <br>} <br></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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template