我需要從“表單”文本輸入中讀取用戶名,并將其顯示在頁面某處的問候訊息中,即你好(用戶)。我需要使用“表單”輸入并使用查詢字串從 URL 中提取用戶名。我還需要在加載頁面時讀取查詢字串,而不是在按下按鈕時讀取,即需要為onload事件撰寫一個函式這一切都必須在一個 HTML 檔案而不是兩個單獨的 HTML 檔案中完成。任何幫助將不勝感激!
<form>
<input type="text" name="user_name" placeholder="Enter your name!">
<button type="submit">Apply!</button>
</form>
uj5u.com熱心網友回復:
// use the ids to access the elements in the DOM
const userName = document.getElementById("user-name");
const output = document.getElementById("output");
// if there query string is not empty
if (location.search !== '') {
// get the parameters
const params = new URLSearchParams(location.search);
// pick out the user name
const un = params.get("user_name");
// update the input and the display
output.textContent = userName.value = un;
}
<form>
<input type="text" id="user-name" name="user_name" placeholder="Enter your name!">
<button type="submit">Apply!</button>
</form>
<p>Hello <output id="output"></output></p>
uj5u.com熱心網友回復:
您可以通過添加“keyup”事件偵聽器來執行此操作。有關示例,請參見下面的代碼片段。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="h1">Hello World</h1>
<form>
<input type="text" name="user_name" placeholder="Enter your name!" id="input">
<button type="submit">Apply!</button>
</form>
<script>
// update the body h1 element with real-time user input
function updateH1() {
var h1 = document.getElementById("h1");
var input = document.getElementById("input");
h1.innerHTML = input.value;
}
// call updateH1() when the user types in the input element
function init() {
var input = document.getElementById("input");
input.addEventListener("keyup", updateH1);
}
// call init() when the page loads
window.addEventListener("load", init);
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/535692.html
上一篇:HTML/PHP輸入多行輸入,我在單行輸入。如何解決?
下一篇:jquery不等待函式的回傳值
