比如我给 a 标签绑定了一个点击事件,我点击你的时候希望你能告诉我你的地址是什么 ,而不是直接跳转链接 ,那么我们就要把 a 标签原先的默认事件阻止,不让他执行默认事件
我们有两个方法来阻止默认事件
e.preventDefault() : 非 IE 使用
e.returnValue = false :IE 使用
我们阻止默认事件的时候也要写一个兼容的写法
var oA = document.querySelector('a')
a.addEventListener('click',function(e){
e = e || window.event
console.log(this.href)//下面这个是兼容写法
e.preventDefault ? e.preventDefault(): e.returnValue =false})
实例
<!DOCTYPEhtml><html><head><metacharset="UTF-8"><title></title><scripttype="text/javascript">
window.onload=function(){//抓取元素var a = document.getElementById("a");
a.onclick=function(e){//获得事件对象var e = e || window.event;//判断浏览器if(document.all){//阻止IE浏览器的默认行为//阻止a标签跳转和from表单的提交
e.returnValue =false;}else{//阻止非IE浏览器的默认行为//阻止a标签跳转和from表单的提交
e.preventDefault()}}}</script></head><body><aid="a"href="http://www.baidu.com">跳转百度</a><ahref="javascript:;">阻止a标签跳转</a><ahref="javascript:viod(0);">阻止a标签跳转</a></body></html>