[英]My array (myLeads) elements are not rendered in HTML list but they are showing correctly in console. I want to print myLeads[ ] elements in HTML list
let myLeads = []; const inputEl = document.getElementById("input-el"); const inputBtn = document.getElementById("input-btn"); const ulEl = document.getElementById("ul-el"); inputBtn.addEventListener("click", function(){ myLeads.push(inputEl.value); console.log(myLeads) }) let arr = [2, 3, "fadf"] /*arr[] elements are rendered correctly in HTML list. But myLeads[] elements are not rendered in HTML list, as they are printed correctly in console.*/ for(let i = 0; i < myLeads.length; i++){ ulEl.innerHTML += "<li>" + myLeads[i] + "</li>" }
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=\. initial-scale=1.0"> <title>save leads</title> <link rel="stylesheet" href="/index.css"> </head> <body> <input type="text" id="input-el"> <button id="input-btn">Save tabs</button> <ul id="ul-el"></ul> <script src="/index.js"></script> </body> </html>
將循環放在 function 中並調用它。 還要確保將 ul 重置為空
let myLeads = []; const inputEl = document.getElementById("input-el"); const inputBtn = document.getElementById("input-btn"); const ulEl = document.getElementById("ul-el"); inputBtn.addEventListener("click", function(){ myLeads.push(inputEl.value); updateList(); }) let arr = [2, 3, "fadf"] /*arr[] elements are rendered correctly in HTML list. But myLeads[] elements are not rendered in HTML list, as they are printed correctly in console.*/ function updateList(){ ulEl.innerHTML = ""; for(let i = 0; i < myLeads.length; i++){ ulEl.innerHTML += "<li>" + myLeads[i] + "</li>" } }
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=\. initial-scale=1.0"> <title>save leads</title> <link rel="stylesheet" href="/index.css"> </head> <body> <input type="text" id="input-el"> <button id="input-btn">Save tabs</button> <ul id="ul-el"></ul> <script src="/index.js"></script> </body> </html>
當點擊事件被觸發時,您不會在任何地方更新 HTML 元素。 這意味着您的列表僅在頁面刷新時由myLeads
的初始元素填充,然后再也不會。
將生成li
元素的循環移動到一個function中,例如
function updateList(arr){
ulEl.innerHTML = "";
for(let i = 0; i < arr.length; i++){
ulEl.innerHTML += "<li>" + myLeads[i] + "</li>"
}
}
然后在事件處理程序中調用它
inputBtn.addEventListener("click", function(){
myLeads.push(inputEl.value);
console.log(myLeads)
updateList(myLeads);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.