如何在无序列表中呈现列表项

How to render list items inside unordered list

我的目标是根据数组的长度呈现数组中的字符串,但不呈现按钮下方的任何内容。你能帮我看看发生了什么事吗?

let myLeads = ["Whosebug.io", "you.com"]
let myLeads = ["Whosebug.io", "you.com"]
const inputEl = document.getElementById("input-el")
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")

inputBtn.addEventListener("click", () => {
    myLeads.push(inputEl.value)
    console.log(myLeads)
})

for (let i = 0; i < myLeads.legnth; i++) {
    ulEl.innerHTML += "<li>" + myLeads[i] + "</li>"
}
<body>
  <input type="text" id="input-el">
  <button id="input-btn">Save Company</button>
  <ul id="ul-el"></ul>
  <script src="index.js"></script>
</body>

您在 for 循环中拼错了长度,这就是它不起作用的原因。另外,我重构了一下,仅此而已。

let myLeads = ["Whosebug.io", "you.com"]
const inputEl = document.getElementById("input-el")
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")

inputBtn.addEventListener("click", () => {
  myLeads.push(inputEl.value)
  //Render()
  Data(inputEl.value)
  console.log(myLeads)
})

function Data(value) {
  ulEl.innerHTML += "<li>" + value + "</li>"
}

function Render() {
  for (let i = 0; i < myLeads.length; i++) {
    Data(myLeads[i])
  }
}

Render()
<body>
  <input type="text" id="input-el">
  <button id="input-btn">Save Company</button>
  <ul id="ul-el">
  </ul>
  <script src="index.js"></script>
</body>

固定码:

let myLeads = ["Whosebug.io", "you.com"];
const inputEl = document.getElementById("input-el");
const inputBtn = document.getElementById("input-btn");
const ulEl = document.getElementById("ul-el");

inputBtn.addEventListener("click", () => {
    myLeads.push(inputEl.value)
    console.log(myLeads)
});

for (let i = 0; i < myLeads.length; i++) {
    ulEl.innerHTML += "<li>" + myLeads[i] + "</li>";
}
<body>
     <input type="text" id="input-el">
     <button id="input-btn">Save Company</button>
     <ul id="ul-el">
     </ul>
     <script src="index.js"></script>
</body>

小错别字

你只打错了一点。在 for 循环中,你输入 legnth 它应该是 length.

您需要在 DOM 上保存更改。下面在每个新条目上创建新的列表元素,并在 DOM.

上添加“保存”
inputBtn.addEventListener("click", () => {
  myLeads.push(inputEl.value);
  let newEl = document.createElement("li");
  newEl.innerText = inputEl.value;

  ulEl.appendChild(newEl);
});

也永远不要在您直接从用户那里得到的东西上使用 innerHTML。很危险。

首先,您的 for 循环中有错字 myLeads.length

我建议创建一个函数来更新 ul 元素,并在按钮的点击事件中调用它。

window.onload = function () {
  let myLeads = ["Whosebug.io", "you.com"];
  const inputEl = document.getElementById("input-el");
  const inputBtn = document.getElementById("input-btn");
  const ulEl = document.getElementById("ul-el");

  inputBtn.addEventListener("click", () => {
    myLeads.push(inputEl.value);
    updateUl();
    console.log(myLeads);
  });

  function updateUl() {
    ulEl.innerHTML = "";
    for (let i = 0; i < myLeads.length; i++) {
      ulEl.innerHTML += "<li>" + myLeads[i] + "</li>";
    }
  }
};