利用JavaScript阻止表单提交的两种方法
在JavaScript中,阻止表单默认提交行为的方法有两种,分别是:
(1)returnfalse
示例代码
<formname="loginForm"action="login.aspx"method="post">
<buttontype="submit"value="Submit"id="submit">Submit</button>
</form>
<script>
varsubmitBtn=document.getElementById("submit");
submitBtn.onclick=function(event){
alert("preventDefault!");
returnfalse;
};
</script>
(2)使用preventDefault()
在标准浏览器中,阻止浏览器默认行为使用event.preventDefault(),而在IE6~8中,使用returnValue属性来实现。
示例代码
<formname="loginForm"action="login.aspx"method="post">
<buttontype="submit"value="Submit"id="submit">Submit</button>
</form>
<script>
varsubmitBtn=document.getElementById("submit");
submitBtn.onclick=function(event){
alert("preventDefault!");
varevent=event||window.event;
event.preventDefault();//兼容标准浏览器
window.event.returnValue=false;//兼容IE6~8
};
</script>
以上就是利用JavaScript来阻止表单提交的两种方法的全部内容,希望本文的内容对大家使用JavaScript有所帮助。
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短