简体   繁体   English

Javascript重定向不起作用

[英]Javascript redirect does not work

The following codes displays the alert, but does not take me to the requested page. 以下代码显示警报,但不会将我带到请求的页面。

function redirect() {
    alert('runs');
    parent.main.document.location = "url.php";
}

I'm using frames, I want the page to load into the frame named 'main'. 我正在使用框架,我希望页面加载到名为“main”的框架中。 Thanks for any help. 谢谢你的帮助。

请使用window.location.href或location.href而不是document.location。

Use this instead: 请改用:

function redirect() {
    alert('runs');
    window.location = "url.php";
}

And for frames you can use it like this: 对于框架,您可以像这样使用它:

top.frames["main"].location.href="url.php";

Hope this helps. 希望这可以帮助。

Sometimes in JavaScript, you may want to redirect a user to another URL. 有时在JavaScript中,您可能希望将用户重定向到另一个URL。 This is often done setting the window.location properly like so: window.location = "http://google.com/'; However, Safari and IE 5.2 for Mac (at least on OSX) behave a little differently than browsers on the PC. I put together this basic test page in order to see which scenarios work and which don't. 这通常是这样设置window.location,如下所示:window.location =“http://google.com/”;但是,Safari和IE 5.2 for Mac(至少在OSX上)的行为与上面的浏览器略有不同PC。我把这个基本测试页面放在一起,以便查看哪些方案有效,哪些无效。

refer this link for the code 请参阅此链接以获取代码

Tests 2, 4 and 5 work but 1 and 3 don't. 测试2,4和5工作,但1和3不工作。 And you can probably see why. 你可能会明白为什么。 In 1 and 3, we set the window.location to a new URL. 在1和3中,我们将window.location设置为新的URL。 This would normally redirect the user to the new page. 这通常会将用户重定向到新页面。 But after the onclick event, it runs the URL contained in the href and overrides the redirect. 但是在onclick事件之后,它会运行href中包含的URL并覆盖重定向。 In this case, the # keeps the page from redirecting altogether. 在这种情况下,#会使页面完全不重定向。 By putting return false; 通过返回false; we stop the href from being processed altogether. 我们阻止href被完全处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM