为何动态创建的按钮无法在<li>标签内显示?求解决方法
问题原因及解决方法
你的代码里按钮不显示的核心问题是:你先把deleteButton添加到li中,随后使用li.textContent = showEvent直接覆盖了li内部的所有内容,包括刚添加的按钮元素,所以按钮被清空了。
解决思路
要避免用textContent直接覆盖整个li的内容,而是把文本和按钮作为独立的子节点添加到li里。下面提供两种可行的修改方案:
方案一:创建文本节点与按钮分别添加
let eventList = []; const inputBox = document.querySelector('.input-field'); const submit = document.querySelector('.submit'); const itemsList = document.querySelector('.list') function addEvent() { const showEvent = inputBox.value; // 过滤空输入 if (!showEvent.trim()) return; const li = document.createElement('li'); const deleteButton = document.createElement('button'); // 设置按钮显示文本 deleteButton.textContent = '删除'; // 创建文本节点并添加到li,再追加按钮 li.appendChild(document.createTextNode(showEvent)); // 加空格分隔文本和按钮 li.appendChild(document.createTextNode(' ')); li.appendChild(deleteButton); itemsList.appendChild(li); eventList.push(showEvent); inputBox.value = ''; } submit.addEventListener('click', addEvent);
方案二:先添加按钮,再用insertAdjacentText插入文本
let eventList = []; const inputBox = document.querySelector('.input-field'); const submit = document.querySelector('.submit'); const itemsList = document.querySelector('.list') function addEvent() { const showEvent = inputBox.value; if (!showEvent.trim()) return; const li = document.createElement('li'); const deleteButton = document.createElement('button'); deleteButton.textContent = '删除'; // 先把按钮添加到li li.appendChild(deleteButton); // 在按钮前插入文本(加空格分隔) deleteButton.insertAdjacentText('beforebegin', showEvent + ' '); itemsList.appendChild(li); eventList.push(showEvent); inputBox.value = ''; } submit.addEventListener('click', addEvent);
补充说明
textContent属性的作用是替换元素内的所有子节点为指定文本,所以当你执行li.textContent = showEvent时,之前添加的button元素会被完全替换成文本,这就是按钮消失的根本原因。
内容的提问来源于stack exchange,提问作者Denis Accardo
相关产品推荐
相关产品推荐

