表单上的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中打开生成的页面,而是在另一个窗口中打开.每次. 整晚让我疯狂. 解决方法五件事:>完全删除表单的目标属性.默认值是相同的窗口.虽然它并不重要,因为: var response = document.getElementById('answer').value; 表单元素没有值.您希望将id放在input type =“text”元素上. 所以: <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> 我建议总是使用一致的,有用的代码缩进,并且我总是喜欢使用块,而不仅仅是语句,带有控制结构. (编辑:ASP站长网) |