我想用一些js保護我的本地靜態html網站密碼,這樣當我在我的電腦上打開我的本地html檔案時,它會附帶一個表格來填寫我的用戶ID和我自己的密碼,我已經保存了我按回車鍵,只有在密碼正確時才會打開我的 index.html 檔案。目前我的代碼是
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<Form>
<!-- user-id -->
<input type="text">
<!-- user-password -->
<input type="password">
<button onclick="window.open('./index.html')"> Enter
</button>
</Form>
<script>
// pls-help-me-idk-how-to-code-js
</script>
</body>
</html> ``
uj5u.com熱心網友回復:
這不是一個正確的方法。您需要一個后端才能正確執行它。但如果它只是為了玩,你可以有一個警告框并比較它們的值:如果正確,它會顯示。
uj5u.com熱心網友回復:
首先,您必須向該輸入添加一個 id 或一個類,以便在腳本部分中選擇它們。之后,您可以選擇它們并添加您想要的任何值。如:
<form>
<!-- user-id -->
<input id="user" type="text" />
<!-- user-password -->
<input id="pass" type="password" />
<button onclick="window.open('./index.html')">Enter</button>
</form>
<script>
document.getElementById("user").value = "UsernameOrId";
document.getElementById("pass").value = "SomePassword";
</script>
為了進行比較,您應該從資料庫或某些服務之類的地方獲取正確的密碼,但由于這純粹是為了學習目的,您可以在腳本中對其進行硬編碼以進行檢查。因此,最終的解決方案可能與此類似:
<body>
<form>
<!-- user-id -->
<input id="user" type="text" />
<!-- user-password -->
<input id="pass" type="password" />
<button id="btn">Enter</button>
</form>
<script>
const myPass = "SomePassword";
document.getElementById("user").value = "UsernameOrId"; // predefining the value simulating is saved and by default filled up
document.getElementById("pass").value = myPass; // predefining the value simulating is saved and by default filled up
const btn = document.getElementById("btn"); // getting the button to control its behavior on click event
btn.addEventListener("click", function () {
const passWhenClickingTheBtn = document.getElementById("pass").value;
if (myPass === passWhenClickingTheBtn) { // checking the value entered for pass
window.open("./index.html");
}
});
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/408319.html
標籤:
