JavaScript 重定向无法正常工作

8

这里有很多相同的问题。我尝试了所有的解决方案,但都没有帮助。

我想用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>

这是我的functions.js代码:

function testUrl()
{

window.location = "content.html";

}

function loginClient()
...//more functions

我也尝试了其他方法:

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)

什么都没用,我在Opera、Firefox(都是在Windows系统)和Chrome(Debian系统)中尝试过。 但如果我设置:

window.open("content.html")

但在新标签中不是解决方案,我需要在同一标签中。
但如果我使用Firebug进行调试并始终点击“步入”,那么所有的解决方案都可以工作。如果在重定向之前设置alert(),它也可以正常工作。
控制台没有显示任何错误。我不知道怎么办,请帮忙。
已解决:感谢@lonesomeday!
这就是解决方案:
$(document).ready(function(){
    $("#loginClient").click(function(event){
      event.preventDefault();
      window.location = "content.html";
    });
});

你想在同一标签页中打开与当前页面相同的链接吗? - Bojan Petkovski
对我来说可以。请检查您是否实际包含了functions.js文件(例如,路径是否正确)。 - Jared Farrish
你的输入 #loginClient 是否在表单内? - Bojan Petkovski
1个回答

9
你在一个 <input type="image"> 元素上添加了 onclick 属性。图像输入实际上是提交按钮。当你单击它时,它会被激活并提交表单。当表单被提交时,它会取消任何正在进行的 HTTP 请求,例如你的 window.location 调用。
因此,你需要阻止表单提交进一步进行。
快速而简便的方法是从你的事件处理程序中返回 false。类似这样:
onclick="return testUrl()" 

使用JS:

function testUrl()
{
window.location = "content.html";    
return false;
}

更好的做法是使用Javascript绑定事件处理程序并使用event.preventDefault


1
只有当“input”位于“form”元素内时才是这种情况。否则,OP的代码可以正常工作,并且不会显示一个“form”本身... - Jared Farrish
@JaredFarrish 它在一个 form 元素中。否则它将无法工作。form 元素明显包含在 ... 中。 - lonesomeday
输入是表单元素。我刚才尝试过返回false; - 不起作用。 - Alexander Tumanin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接