![](/img/trans.png)
[英]How to generate HTML using template literal with data coming from an object literal in JavaScript?
[英]Javascript object not storing data coming from HTML
我從 HTML 給出兩個輸入標題和狀態。 Javascript 正在偵聽輸入並創建一個emptyObj object 來存儲值,然后將其附加到對象列表objList中。
如果我第一次給出輸入標題:“Node JS”和狀態:“Pending” ,那么會發生一些事情,偵聽器工作正常,我可以在objList中看到它們。 但是下次如果我將新項目附加到列表中,最后一個輸入就會消失,只顯示新的。
輸入 -- HTML 頁
HTMML代碼——
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0">
<title>Document</title>
<style>
#title, #status{
display: block;
width: 200px;
}
</style>
</head>
<body>
<div class="divFirst">
</div>
<button>You are seeing the pending tasks, please click the button to see completed!</button>
<input type="text" id="title" placeholder="Please enter the title of the task">
<input type="text" id="status" placeholder="Please enter the status of the task">
<script src="DOM.js"></script>
</body>
</html>
javascript 代碼 --
let objList = [{
title: "HTML",
status: "Completed"
},{
title: "CSS",
status: "Completed"
},{
title: "Javascript",
status: "Pending"
},{
title: "React Js",
status: "Pending"
},{
title: "Mongo DB",
status: "Pending"
}]
let emptyObj = {
title: "",
status: ""
}
document.querySelector('#title').addEventListener('change',function(e){
emptyObj.title = e.target.value
console.log(e.target.value)
})
document.querySelector('#status').addEventListener('change',function(e){
emptyObj.status = e.target.value
console.log(e.target.value)
})
objList.push(emptyObj)
現在,我怎樣才能永久存儲來自輸入的值?
提前致謝!!!
當您在兩個不同的字段上使用兩個 onchange 方法時,您總是會弄錯第二個更改。 因為它會更改標題然后插入。 您應該使用一個按鈕來更新您的列表。
我認為您可以通過在兩個輸入下添加按鈕來實現您的要求
<button id="updateList" onclick="insertEmpty(emptyObj)">Update List</button>
和下面的 function 到 DOM.js
function insertEmpty(emptyObj)
{
objList.push(emptyObj)
console.log(objList);
}
刪除你的
objList.push(emptyObj) // which is currently at the end of your DOM.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.