表单上的Javascript重定向根据输入提交

tpi*_*man 7 html javascript forms

我正在进行一个简单的javascript测验,我无法为我的生活获取Javascript提交表单并在同一页面打开结果,无论我是否使用location.href,open.window,或者是否我将"_self"设为目标.我做什么似乎并不重要......

function answer() {
  var response = document.getElementById('answer').value;
  if (response == "correctanswer")
    location.href('right.html');
  else
    location.href('wrong.html');
}
Run Code Online (Sandbox Code Playgroud)
<form onSubmit="answer()" id="answer" target="_self">
  <input type="text" maxlength="55" class="box" autofocus />
  <input type="submit" class="submit" value="SUBMIT" />
</form>
Run Code Online (Sandbox Code Playgroud)

所以,我想发生什么,当用户提交表单,他们去"right.html"如果他们输入correctanswer到文本框中,或"wrong.html"如果他们输入任何东西.

我已经把它运行得很好了,除了这样的事实,无论我做什么,我都无法将结果页面打开_self,而是在另一个窗口中.每次.

整晚让我疯狂.

T.J*_*der 21

五件事:

  1. 完全删除target属性form.默认值是相同的窗口.虽然它并不重要,因为:

  2. 由于您在自己的代码中处理表单,因此请在您submit的内容中返回false来取消活动onSubmit.一个简单的方法是让函数返回false,然后onSubmit返回调用的结果.

  3. 这行不正确:

    var response = document.getElementById('answer').value;
    
    Run Code Online (Sandbox Code Playgroud)

    form元素没有value.你会希望把idinput type="text"元素来代替.

  4. hreflocation是不是一个函数,这是一个性质.您只需分配给它(或直接分配给它location).

  5. 这个有点微妙:因为你有一个调用的全局函数answer,并且你有一个带有id "answer"a 的元素,就会发生冲突:两者都希望最终成为window对象的属性(不使用旧DOM0 onxyz属性的全部原因之一- 或全局功能,来吧).因此,您需要更改其中一个的名称,例如,将功能更改为checkAnswer或类似.

所以:

<form onSubmit="return checkAnswer();">
<input id="answer" type="text" maxlength="55" class="box" autofocus />
<input type="submit" class="submit" value="SUBMIT" />
</form>
Run Code Online (Sandbox Code Playgroud)

和:

function checkAnswer(){
    var response = document.getElementById('answer').value;
    if (response == "correctanswer")
        location = 'right.html';
    else
        location = 'wrong.html';
    return false;
}
Run Code Online (Sandbox Code Playgroud)

完整示例:实时复制 | 直播源

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <form onSubmit="return checkAnswer();">
  <input id="answer" type="text" maxlength="55" class="box" autofocus />
  <input type="submit" class="submit" value="SUBMIT" />
  </form>
  <script>
  function checkAnswer(){
      var response = document.getElementById('answer').value;
      if (response == "correctanswer")
          location = 'http://jsbin.com/ukifoh/1'; // 'right.html';
      else
          location = 'http://jsbin.com/ukifoh/2'; // 'wrong.html';
      return false;
  }
  </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我建议总是使用一致的,有用的代码缩进,并且我总是喜欢使用块,而不仅仅是语句,带有控制结构.