js 阻止浏览器默认行为

本文详细介绍了在HTML中如何使用return false来阻止表单提交等默认行为,并通过实例展示了在不同场景下return false的具体应用。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<a href="javascript:;">aa</a>
<a href="" onclick="return false;">bb</a>


<!-- return false只有在行内标签内才起作用-->
<form action="http://www.baidu.com" onsubmit="return false;">
用户名:
<input type="text">
<input type="submit"></form>

 

<!-- 行内是函数时return false的用法 -->
<form action="http://www.baidu.com" onsubmit="return check()" style="margin-top: 20px;">
密码:
<input type="text" id="tex1">
<input type="submit"></form>


<!-- 在标签外给标签加事件 ,,这时也可以用return false 但最好用event.preventDefault();-->
<form action="http://www.baidu.com" id="form1" style="margin-top: 20px;">
校验:
<input type="text" id="tex2">
<input type="submit"></form>

</body>
<script>
function check(){
var oTex=document.getElementById('tex');
if(oTex.value){
return ture;
}else{
event.preventDefault();
}
}
</script>

<script>
var oForm=document.getElementById('form1');
oForm.onsubmit=function(event){
var oTex2=document.getElementById("tex2").value;
if (!oTex2) {
event.preventDefault();
}
}
</script>
</html>

转载于:https://www.cnblogs.com/chabai/p/5368909.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值