为什么我的“ window.location =”行不起作用?

时间:2018-10-10 22:40:28

标签: javascript

我对编码非常陌生。抱歉,这是一个简单的或令人讨厌的基本问题(这是我第一次在此处发布)。我不知道为什么我的JavaScript不能正常工作,而且我也不知道要用什么资源自行寻找,对我而言似乎是一种奇怪的情况。

这是我的代码:

var correct = "password";                                   //Set "correct" to the correct password

  function isenter(){                                             
      var pressed = event.which;                                  
      if (pressed === 13){                                    //If key pressed is "Enter"
          var pwinput = document.getElementById("pw").value;  //Set "pwinput" to the value of the password input field (id="pw")
          window.alert(correct + " " + pwinput);              //Display values of correct and entered password (for debugging)
          if (pwinput === correct) {                          //If entered password is equal to correct password
              window.alert("Match registered");               //Display "Match Registered" (for debugging)
             window.location = "lobby.html";                 //Redirect to another page (THIS IS WHAT ISN'T WORKING)
         }
         else{
             window.alert("Match NOT registered")            //Display "Match NOT registered" (for debugging)
         }
     }
 }

 window.addEventListener("keypress", isenter)                //Listen for keypresses. Run isenter when keys are pressed

页面将不会重定向(第10行)。我想不出为什么不会。它正上方的行确认已注册了匹配项,并且该特定代码分支实际上正在运行,但是第10行由于某种原因无法正常工作。如果我ctrl-x第10行并将其粘贴在第4行和第5行之间,则它可以正常工作(每按一个键即可重定向到新页面),告诉我它应该工作,但由于某种原因而不是其位置。我唯一能想到的是,在“ if”语句中阻止其正常工作,但是我不知道为什么会这样……

任何帮助将不胜感激!再次,这是我第一次在这里发布。如果我违反任何协议或约定,或者我的代码很残破,对不起。先感谢您!我知道我可能缺少一些愚蠢的基本知识。

更新:
我注意到当我更改...

if (pwinput === correct) {

...到...

if (pwinput === "") {

...然后,只要我按“ Enter”,重定向就会成功。似乎该字段不为空会以某种方式阻止重定向。我仍然不确定发生了什么。希望这些补充信息对您有所帮助!

更新两次:
从“ pw”输入周围删除一对“ form”标签后,代码现在可以按预期工作。我目前正在尝试找出如何在不删除表单标签的情况下正常工作。

根据@tim的建议,我已将表单改为使用“ onsubmit”。这稍微简化了我的代码,但是我仍然遇到相同的问题。重定向周围的代码正在运行,但是重定向本身不起作用。这是一个内嵌javascript的准系统html示例。我有一个表单,一个按钮和一个链接。链接和按钮可以正常工作,但表单仍不会重定向。

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
    <title>First Page</title>
</head>
<body>
    <form id="pwform" name="myform">
        <input id="pw" type="password">
    </form>
    <button id="btn">run test function</button>
    <a href="newpage.html">link to next page</a>
<script type="text/javascript">
    function testfunction(){
        window.alert("Test function ran.");   //Verify that testfunction is running.
        window.location ="newpage.html";      //Redirect (works on button, not on form)
    }



    document.getElementById("pwform").onsubmit = testfunction;    // <-- I don't know what the
    document.getElementById("btn").onclick = testfunction;        // <-- difference between these is.
</script>
</body>
</html>

我很困惑,因为我认为我没有理由期望从按钮运行的代码和从提交表单运行的代码有所不同。提交表单时,会弹出警报,确认代码正在运行,但是重定向本身不起作用。

是否存在语法或我未遵循的内容?

附录:
我知道这不是密码的“正确”方法。我只是在一些基础知识上得到练习。

2 个答案:

答案 0 :(得分:0)

我始终使用window.location.replace("relative path to link");,因为它可以在Google Chrome,Firefox和Microsoft Edge上使用!但这对您不起作用,请尝试document.location.assign("link");document.location.replace("link");

来源:

Location.Assign

Location.Replace

现在我知道这不是问题的一部分,但是根据Mozilla Docs for JavaScript,控制键码的最佳方法不是event.which,而是实际上是event.key。 这是Key Codes的列表,可用于if (event.key === "a"),这是如何使用event.key

我刚才回答了一个问题:here

为什么不用keypress来解决所有麻烦,为什么不只使用form?单击任何按钮或按回车键都会自动触发提交,并且移动设备更加友好。您要做的就是停止使用javascript:void(0);进行重新路由,并使用onsubmit事件来触发您的功能。

<form action="javascript:void(0);" onsubmit="login()">
    <table>
        <tr>
            <td>Username:</td>
            <td><input type="text" placeholder="Username..." /></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="password": placeholder="Password..." /></td>
        </tr>
        <tr><td colspan="2"><button>Submit</button></td></tr>
    </table>
</form>
<script>
    function login() {
        //Login Code Here
    }
</script>

答案 1 :(得分:0)

您需要将event传递给函数参数。我检查了上面链接的unk子,这似乎是您的问题。您只需要将function isenter() { ... }更改为function isenter(event) { ... },因为您要在函数中使用event.which。这是分叉的小提琴:https://jsfiddle.net/ot7863xe/

 function isenter(event){ // <--------------- add event here                                            
          var pressed = event.which;                                  
          if (pressed === 13){                                    //If key pressed is "Enter"
              var pwinput = document.getElementById("pw").value;  //Set "pwinput" to the value of the password input field (id="pw")
              window.alert(correct + " " + pwinput);              //Display values of correct and entered password (for debugging)
              if (pwinput === correct) {                          //If entered password is equal to correct password
                  window.alert("Match registered");               //Display "Match Registered" (for debugging)
                 window.location = "lobby.html";                 //Redirect to another page (THIS IS WHAT ISN'T WORKING)
             }
             else{
                 window.alert("Match NOT registered")            //Display "Match NOT registered" (for debugging)
             }
         }
     }

根据答案更新

您无需删除表单标签即可使其正常工作。如果将onsubmit处理程序附加到表单,则可以注册提交的函数,以便在提交表单时执行该函数。这样,您还可以消除为跟踪用户是否已按下“ enter”而编写的代码,并且也可以摆脱window.addEventListener,从而不必跟踪每次按键。在此处查看jsFiddle:https://jsfiddle.net/ot7863xe/

我做到了,以便表单使用onsubmit处理程序,并且当用户按下Enter时,您的函数就会执行。

更新2以允许表单重定向

您必须在action="newpage.html"元素中添加form,以便form知道要去哪里。您的isenter函数和最新更新的testFunction应该处理返回truefalse所必需的逻辑,以便表单可以重定向或不重定向。如果您的函数返回true,则表单将内联查看action并转到该页面。另一方面,如果函数返回false,则form将被阻止提交(并且将不会重定向)。

因此,请注意以下内容,我在您的action标记中添加了form,并使您的testFunction返回true,以便重定向将在表单提交时发生。如果将返回值更改为false,将不会发生任何事情。

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
    <title>First Page</title>
</head>
<body>
    <form id="pwform" name="myform" action="newpage.html" onsubmit="testfunction()">
        <input id="pw" type="password">
        <button type="submit" id="btn">run test function</button>
    </form>

<script type="text/javascript">
    function testfunction(){
        window.alert("Test function ran.");   //Verify that testfunction is running.
        //window.location.replace("newpage.html");      //Redirect (works on button, not on form)
        return true;
    }



    document.getElementById("pwform").onsubmit = testfunction;    // <-- I don't know what the --> it attaches handler to the form (which you don't need to do - you can just specify that inline in the form like above)
    //document.getElementById("btn").onclick = testfunction;        // <-- difference between these is --> it adds a click handler directly to the button element (not the form).
</script>
</body>
</html>
相关问题