夺命雷公狗---javascript NO:17 默认行为2

解决兼容性问题

① 在public.js中创建prevent函数

② 判断浏览器类型

③ 编写一下程序代码

//解决阻止默认行为兼容性问题
function prevent(event){
    if(window.event){
        //IE模型浏览器
        window.event.returnValue = false;
    }else{
        //w3c
        event.preventDefault();
    }
}

④ 在html页面测试prevent方法

<!DOCTYPE html>
<html>
<head>
<meta charset=’utf-8′>
<title></title>
<script src=’public.js’></script>
<script>
window.onload = function(){
$(‘btnok’).onclick = function(){
if($(‘username’).value == ”){
alert(‘用户名不能为空’);
//IE模型
//window.event.returnValue = false;
//w3c模型
//event.preventDefault();
prevent(event);
}
}
}
</script>
</head>
<body>
<form action=”4.html” method=”post”>
name:<input type=”text” id=”username”>
<hr/>
<input type=”submit” id=”btnok” name=”submit” value=’注册’>
</form>
</body>
</html>
原文地址:https://www.cnblogs.com/leigood/p/5031904.html