JavaScript实现输入框排序和删除功能
以下是一个基于JS实现的输入框、排序和删除功能的示例代码:
HTML代码:
<label for='inputText'>输入一段话:</label>
<input type='text' id='inputText'>
<button id='addButton'>添加</button>
<ul id='list'></ul>
JS代码:
const inputText = document.getElementById('inputText');
const addButton = document.getElementById('addButton');
const list = document.getElementById('list');
let items = [];
addButton.addEventListener('click', () => {
const newItem = inputText.value.trim();
if (newItem) {
items.push(newItem);
renderList();
inputText.value = '';
}
});
function renderList() {
// Sort items alphabetically
items.sort();
// Clear existing items
while (list.firstChild) {
list.removeChild(list.firstChild);
}
// Create new list items and add to list
items.forEach((item, index) => {
const li = document.createElement('li');
li.textContent = `${index + 1}. ${item}`;
const deleteButton = document.createElement('button');
deleteButton.textContent = '删除';
deleteButton.addEventListener('click', () => {
items.splice(index, 1);
renderList();
});
li.appendChild(deleteButton);
list.appendChild(li);
});
}
该代码将输入框中的文本存储到数组中,并在每次添加或删除元素时更新页面上的列表。它还包括对元素的排序功能。
原文地址: https://www.cveoy.top/t/topic/oLBr 著作权归作者所有。请勿转载和采集!