我试图在用户浏览器启用javascript时将“我的个人资料”菜单链接重定向到自定义网址。我已经编写了一个自定义url来创建动态函数getNewURL(),并且连接工作正常。问题是,即使启用了JavaScript(在我的Chrome上),href中的默认页面也会加载,尽管所有默认防护代码都是如此。我一直在这花费数小时,并且无法弄清楚问题所在。任何帮助将不胜感激。Javascript的默认事件预防不起作用
<head>
<script type="text/javascript">
<!--
function init() {
document.getElementById('profile').onclick=getNewURL;
}
window.onload=function(){
init();
}
function getNewURL(e)
{
if(!e) e = window.event;
var a = 'http://www.google.com/';
var b = 'advanced_search?hl=en';//this will actually be a dynamic wikispaces
//variable - the username.
var url = a+b;
window.location.href = url;
//Over-riding default action
//e.cancelBubble is supported by IE
e.cancelBubble = true;
e.returnValue = false;
//e.stopPropagation works only in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
}
e.preventDefault();
return false;
}
//-->
</script>
</head>
<body>
<div id="menu">
<ul>
<li><a href="http://www.google.com/" id="profile">My Profile</a></li>
</ul>
</div>
</body>
你e.preventDefault是你的支票e.stopPropagation内。所以当你不在Firefox上不这样做。如果你将它移到if语句之外,它应该在chrome中工作 – Ryan 2012-04-15 23:55:23
我曾经希望那是它,但可悲的是它不是。默认预防仍然不起作用。 – zeqof 2012-04-16 00:26:48
我没有看到你在调用你的'init'方法。 – 2012-04-16 00:29:17