簡體   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