这里有很多相同的问题.我尝试了所有的解决方案 - 没什
我想用javascript在一些标签页面打开新页面.这是我的HTML:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" ></script>
<script src="functions.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link href="css.css" rel="stylesheet" type="text/css" />
</head>
<body>
...
<label>
<input type="image" name="imageField" id="loginClient" onclick="testUrl()" src="images/index_33.gif" />
</label>
...
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这是我的functions.js:
function testUrl()
{
window.location = "content.html";
}
function loginClient()
...//more functions
Run Code Online (Sandbox Code Playgroud)
我也尝试了其他方法:
window.location.replace("content.html")
top.location="content.html"
window.location.assign("content.html")
window.open("content.html", "_self")
window.location.href="content.html"
window.event.returnValue = false;
window.location = "content.html";
setTimeout(function(){window.location.assign("content.html");return false;},500)
Run Code Online (Sandbox Code Playgroud)
没有用,我在Opera,Firefox(全部在Windows)和Chrome(Debian)中尝试过.但如果我设置:
window.open("content.html")
Run Code Online (Sandbox Code Playgroud)
但在新标签中,不是解决方案,我需要在同一个标签中.
但是,如果我尝试使用Firebug进行调试并点击始终"Step into"而不是所有解决方案的工作.如果我在重定向之前设置alert(),它也可以.
控制台显示没有错误.我不知道,帮帮忙.
决议:感谢@lonesomeday!
这是解决方案:
$(document).ready(function(){
$("#loginClient").click(function(event){
event.preventDefault();
window.location = "content.html";
});
});
Run Code Online (Sandbox Code Playgroud)
你onclick在一个<input type="image">元素上有这个属性.图像输入实际上是submit按钮.单击它时,它将被激活,并提交表单.提交表单时,它会取消任何正在进行的HTTP请求,例如您的window.location呼叫.
因此,您需要阻止表单提交继续进行.
快速而肮脏的方法是false从事件处理程序返回.像这样的东西:
onclick="return testUrl()"
Run Code Online (Sandbox Code Playgroud)
随着JS:
function testUrl()
{
window.location = "content.html";
return false;
}
Run Code Online (Sandbox Code Playgroud)
更好的方法是使用Javascript绑定您的事件处理程序并使用event.preventDefault.