重定向到本地html文件不会在同一窗口中打开

时间:2016-12-17 13:51:32

标签: 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”)不起作用,我认为这是因为我的文件在localhost上运行。

2 个答案:

答案 0 :(得分:1)

您的代码无效的完整答案是因为您拥有的按钮正在提交表单。从单击侦听器返回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();
});

这适用于相同的想法,但改为停止提交表单的按钮的默认行为。

答案 1 :(得分:0)

尝试使用标记 像这样:

<a href="/myprojects/L2/selectYourCharacter/selectYourCharacter.html" style="text-direction:none">
     <button>Your Button Text</button>
</a>