Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

html - javascript redirect not working anyway

There are many same questions here. I tried all solutions - nothing helps.

I want to open new page in some tab with javascript. Here is my 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>

Here is my functions.js:

function testUrl()
{

window.location = "content.html";

}

function loginClient()
...//more functions

I tried other ways too:

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)

nothing works, I tried it in Opera, Firefox (all in Windows) and Chrome (Debian). BUT it works if I set:

window.open("content.html")

but in new tab, isn't solution, I need it in same tab.

BUT if I try to debug it with Firebug and click always "Step into" than all solution work. And if I set alert() before redirecting, it works too.

Console shows no errors. I have no idea, help.

RESOLVED: Thanks to @lonesomeday!

this is the solution:

$(document).ready(function(){
    $("#loginClient").click(function(event){
      event.preventDefault();
      window.location = "content.html";
    });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've got this onclick attribute on an <input type="image"> element. Image inputs are effectively submit buttons. When you click it, it is activated, and the form is submitted. When a form is submitted, it cancels any ongoing HTTP requests, such as your window.location call.

So you need to prevent the form submission from going ahead.

The quick and dirty way to do this is to return false from your event handler. Something like this:

onclick="return testUrl()" 

With the JS:

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

The prettier way to do this would be to bind your event handlers with Javascript and use event.preventDefault.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...