繁体   English   中英

我如何制作一个使用特定输入重定向到特定 html 页面的 js 代码?

[英]How do i make a js code that redirects to a certain html page with a certain input?

让我更好地解释一下,我想知道如何创建一个 js 代码来检查 html 输入是否正确,如果它会将您重定向到另一个页面,这是我根据我设法做到的尝试找出。

html部分:

<form name="access" onsubmit="return validate()">
  <input
    type="text"
    id="inputbox"
    value="Password"
    pattern="idkwhatishoouldwriteinhere"
  />
  <input type="submit" value="Submit" />
</form>

js部分:

function validate() {
  if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
    alert("Wrong password");
    document.access.Password.focus();
    return false;
  } else {
    window.open("index.html");
  }
}

如果你想知道为什么我把“答案”放在模式中是因为这应该是一个小复活节彩蛋,我觉得直接查看 js 是没有意义的,因为它包含你应该被重定向到的链接。 在这里输入代码

您需要输入名称Password ,否则document.access.Password未定义。

 function validate() { if (document.access.Password.value != "idkwhatishoouldwriteinhere") { alert("Wrong password"); document.access.Password.focus(); return false; } else { window.open("index.html") } }
 <form name="access" onsubmit="return validate()"> <input type="text" id="inputbox" value="Password" name="Password" /> <input type="submit" value="Submit" /> </form> <!-- password is "idkwhatishoouldwriteinhere" -->

你要这个。

您在字段 ID 和名称等方面遇到了一些问题

我还将您的内联代码更改为 eventListener,这是推荐的方法

密码是fred

 window.addEventListener("load", function() { document.getElementById("access").addEventListener("submit", function(e) { const inputbox = document.getElementById("inputbox"); if (inputbox.value != "fred") { alert("Wrong password"); inputbox.focus(); e.preventDefault(); // cancel submit } else location.replace("index.html") }); })
 <form id="access"> <input type="password" id="inputbox" value="" placeholder="Password" /> <input type="submit" value="Submit" /> </form>

如果你想让你的代码接近你已经拥有的代码,我会像这样调整它。 我建议将您的类名和 id 存储为变量,然后从变量中访问它们。 也没有必要在你的 if 中返回 false。 这里还有其他很好的解决方案,但这个解决方案将使您的代码非常接近。 这也将确保您在访问密码字段中的值时不会得到空值。

 const passwordField = document.getElementById('inputbox'); function validate() { if(passwordField.value != "idkwhatishoouldwriteinhere") { alert( "Wrong password" ); passwordField.focus() ; } else { window.open("index.html") } }
 <form name="access" onsubmit="validate()" href="javascript:void(0)"> <input type="text" id="inputbox" value="Password" /> <input type="submit" value="Submit" /> </form>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM