为什么我的按钮没有显示在 li 标签内?

问题描述 投票:0回答:1

我想在

<li></li>
中添加一个按钮(deleteButton),之前创建并附加到
<ol>

我的代码:

let eventList = [];
const inputBox = document.querySelector('.input-field');
const submit = document.querySelector('.submit');
const itemsList = document.querySelector('.list')

function addEvent() {
  const showEvent = inputBox.value;

  const li = document.createElement('li');
  const deleteButton = document.createElement('button');
  itemsList.appendChild(li);
  li.appendChild(deleteButton);


  eventList.push(showEvent)
  li.textContent = showEvent;
  inputBox.value = '';
}

submit.addEventListener('click', addEvent);
<h1>TO-DO LIST</h1>
<input class="input-field" type="text">
<button class="submit" type="button">ADD TO-DO</button>
<ol class="list"></ol>

按钮根本没有显示。我该怎么做才能让它显示在 li 元素中?

javascript html html-lists
1个回答
0
投票
let eventList = [];
const inputBox = document.querySelector('.input-field');
const submit = document.querySelector('.submit');
const itemsList = document.querySelector('.list');

function addEvent() {
  const showEvent = inputBox.value;

  const li = document.createElement('li');
  const deleteButton = document.createElement('button');
  deleteButton.textContent = "Delete";
  li.appendChild(deleteButton);
  itemsList.appendChild(li);

  eventList.push(showEvent);
  li.textContent = showEvent;
  inputBox.value = '';

  deleteButton.addEventListener('click', () => {
    itemsList.removeChild(li);
    eventList.splice(eventList.indexOf(showEvent), 1);
  });
}

submit.addEventListener('click', addEvent);

更新后的代码,我们创建一个删除按钮元素,将其文本内容设置为“Delete”,并将其附加为

<li>
元素的子元素。我们还为删除按钮添加了一个事件监听器,它从列表中删除
<li>
元素,并从 eventList 数组中删除相应的事件。

© www.soinside.com 2019 - 2024. All rights reserved.