我正在嘗試創建一個函式,以便在提交表單時將用戶填寫的詳細資訊(即他/她的姓名和電子郵件 ID)附加到串列/陣列中。然后顯示串列/陣列。
例如...
當我第一次填寫憑據時:
姓名 -
電子郵件 - [email protected]
提交表單的輸出應該是:
[["A", "[email protected]"]]
第二次填寫憑據時:
姓名-B
郵箱[email protected]
提交表單的輸出應該是:
[["A", "[email protected]"], ["B", "[email protected]"]]
但是當我嘗試這個時,我沒有得到串列/陣列的輸出。這是我嘗試過的...
const info = [];
function display(){
var nm = document.getElementById("nm").value;
var em = document.getElementById("em").value;
var data = [nm, em];
info.push(data);
var text = document.createElement("h2");
text.innerHTML = info;
}
<body>
<script src="script.js"></script>
<form onsubmit="return(display())">
<input type="text" placeholder="Name" id="nm">
<input type="email" placeholder="Email" id="em">
<input type="submit" value="Submit">
</form>
</body>
uj5u.com熱心網友回復:
它不顯示資料的原因有兩個。
每次提交表單時,它都會重繪 頁面。為了防止這種情況,您必須阻止按鈕提交的默認操作。這可以通過事件使用函式 preventDefault() 來完成。在代碼中更好地解釋。
您尚未將創建的元素附加到任何元素,因此它不會顯示在網頁上的任何位置。
兩者都可以通過檢查代碼和下面的解釋來解決!
const info = [];
function display(e){ // the `e` parameter is the event passed in.
e.preventDefault(); // We run the function preventDefault to prevent the page from reloading.
var nm = document.getElementById("nm").value;
var em = document.getElementById("em").value;
var data = [nm, em];
info.push(data);
var text = document.createElement("h2");
text.innerHTML = info;
document.body.appendChild(text); // You haven't appended the information to
// anything, here I append the created Element to the Body so it displays, but do note, that this displays
// the full list, you may want to change this to display only the newer data
// or perhaps append to a element that prints out each time a new user is added.
//console.log(info); You can see that the array now updateds in the console.
}
<script src="script.js"></script>
<!-- Pass the event of submitting a form as an argument -->
<form onsubmit="display(event)">
<input type="text" placeholder="Name" id="nm">
<input type="email" placeholder="Email" id="em">
<input type="submit" value="Submit">
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367429.html
標籤:javascript html 列表 形式 功能
