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

正在进行一个简单的 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');
}
<form onSubmit="answer()" id="answer" target="_self">
  <input type="text" maxlength="55" class="Box" autofocus />
  <input type="submit" class="submit" value="SUBMIT" />
</form>

所以,我想要发生的是,当用户提交表单时,如果他们在文本框中键入了正确的答案,他们会转到“right.html”,如果他们输入了其他内容,则会转到“wrong.html”.

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

整晚让我疯狂.

解决方法

五件事:

>完全删除表单的目标属性.认值是相同的窗口.虽然它并不重要,因为:
>通过在onSubmit中返回false来取消提交事件,因为您在自己的代码中处理表单.一种简单的方法是让函数返回false,并在onSubmit中返回调用的结果.
>这一行不正确:

var response = document.getElementById('answer').value;

表单元素没有值.您希望将id放在input type =“text”元素上.
>位置上的href不是函数,它是属性.您只需分配给它(或直接分配给位置).
>这个有点微妙:因为你有一个名为answer的全局函数,并且你有一个id为“answer”的元素,就会发生冲突:两者都希望最终成为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>

和:

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

完整示例:Live Copy | Live Source

<!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>

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

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些