javascript - 重定向到本地 html 文件无法在同一窗口中打开

标签 javascript redirect localhost

我知道有人问过类似的问题,但经过各种测试,似乎没有人能工作。我认为这与我尝试使用 js 从本地 html 文件重定向到另一个本地 html 文件有关。

我的creationPage.html中的按钮:

      <form>
          <button id="createChar">Create character</button> 
      </form>

我的 js 文件中的重定向代码:

var Create = document.getElementById('createChar');

  Create.addEventListener("click", function() {

    //window.open(url); //opens in a new tab, WHICH IS NOT DESIRED !!!
    //window.location.replace(url); //doesnt work either.

  var url = "http://localhost/myprojects/L2/selectYourCharacter/test.html";
    window.location.href = url;
    return false;
});

我想坚持使用 addListenerEvent 作为最佳实践。如果我运行 window.open(url, "_blank"),它不起作用。

摘要:我想通过位于 http://localhost/myprojects/L2/charCreation/creationPage.html 的按钮进行重定向至http://localhost/myprojects/L2/selectYourCharacter/selectYourCharacter.html停留在同一个窗口中。

非常感谢您的帮助,因为我已经被这个问题困扰了几个小时......

注意:window.open("www.youraddress.com","_self") 不起作用,我认为这是因为我的文件在本地主机上运行。

最佳答案

为什么您的代码不起作用的完整答案是因为您的按钮正在提交表单。从点击监听器返回 false 只是告诉浏览器您没有处理点击。

这段代码;

var Form = document.getElementById('form');

Form.addEventListener("submit", function(e) {

    //window.open(url); //opens in a new tab, WHICH IS NOT DESIRED !!!
    //window.location.replace(url); //doesnt work either.

    var url = "http://localhost/myprojects/L2/selectYourCharacter/test.html";
    window.location = url;
    e.preventDefault();
});

会起作用,因为它将停止表单的默认提交行为。该按钮提交表单,您可以处理提交事件来执行您希望它执行的操作。

另外:

var Create = document.getElementById('createChar');

Create.addEventListener("click", function(e) {

    //window.open(url); //opens in a new tab, WHICH IS NOT DESIRED !!!
    //window.location.replace(url); //doesnt work either.

    var url = "http://localhost/myprojects/L2/selectYourCharacter/test.html";
    window.location = url;
    e.preventDefault();
});

这具有相同的想法,但会停止按钮的默认行为,即提交表单。

关于javascript - 重定向到本地 html 文件无法在同一窗口中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41199282/

相关文章:

javascript - react index.html 呈现但 react 组件不

javascript - FlipClock JavaScript 问题

javascript - PHP下拉框存储选择的值

将唯一身份访问者重定向到备用主页?

php - 为什么我的 htaccess 代码不起作用?

javascript - 将对象展平为数组?

android - 如何重定向回 Android 应用程序?

javascript - 关于开始node.js的一些问题

asp.net - 找不到本地主机 (404) iis

asp.net-mvc - ASP.NET MVC : How to automatically disable [RequireHttps] on localhost?