`

在IE6下 a标签添加行间onclick事件导致页面跳转失败原因分析

阅读更多



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Js在IE6下 a标签添加行间onclick事件导致js跳转失败的元凶, href="javascript:void(0);"</title>

<style type="text/css">
* {margin:0;padding:0;margin:0 auto;}
</style>
</head>

<body>
<br />
<p> href="javascript:void(0);" 和 href="javascript:;" 的写法没关系</p> <br />

<p> location.replace 和 location.href 的区别: </p>
<p> 在IE、chorome 条件下 location.replace 不能点回退, Firefox则可以回退 </p>
<p> 在IE、chorome、Firefox 条件下location.href 都能点回退 </p>
 <br />
<p> 1  href="javascript:void(0);" </p> <br />
<a href="javascript:void(0);" onclick="javascript:location.replace ('http://www.baidu.com/');">a IE6不能跳转 </a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href="javascript:void(0);" onclick="javascript:location.href ='http://www.baidu.com/';">a IE6不能跳转 </a>  
 <br /><br /><br />
<p> 2  href="javascript:;" </p> <br />
<a href="javascript:;" onclick="javascript:location.replace ('http://www.baidu.com/');">a IE6不能跳转 </a>  &nbsp;&nbsp;&nbsp;&nbsp;
<a href="javascript:;" onclick="javascript:location.href ='http://www.baidu.com/';">a IE6不能跳转 </a>  
 <br /> <br /><br />
<p>1 第一种写法 直接给对象添加事件,节点添加事件  </p>
<p>2 第二种写法 这种情况更加动态,addEventListener || attachEvent 更为实用,  </p>
<p>  而且还能添加多个函数(添加的事件的顺序即执行顺序)----->执行顺序不同浏览器不同!但是我们希望是顺序执行!  </p>
<a id="a1" href="javascript:;"> a 能跳转 </a>&nbsp;&nbsp;&nbsp;&nbsp;
<a id="a2" href="javascript:;"> a 能跳转 </a>  <br /> <br />

<p> add return false;  </p>
<a href="javascript:void(0);" onclick="javascript:location.replace ('http://www.baidu.com/'); return false;">a 能跳转 </a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href="javascript:void(0);" onclick="javascript:location.href ='http://www.baidu.com/'; return false;">a 能跳转 </a>
<script type="text/javascript">

var oA1 = document.getElementById("a1");
var oA2 = document.getElementById("a2");

oA1.onclick = oA2.onclick = function(){
	oA1.href = oA2.href = "http://www.baidu.com";
	//return false; //加了就不能跳转了。
};


</script>
</body>
</html>




经测试,在IE6下上述两种JS跳转履行无响应,其它浏览器下均正常。

解析:猜测IE6下a链接的跳转会收到href属性中代码的影响,

上述代码的履行过程,貌似是先履行 onclick事务中的代码,

并且是在onclick事务的回调函数返回true 的景象下,

再履行href属性中的代码,然后才作出跳迁移转变作。

而恰是void(0);代码阻拦了浏览器跳转,所以在onclick的代码最后,加上return false;

让onclick回调函数返回false值,以阻拦履行 href属性中的代码,如许就可以让浏览器顺利跳转。



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics