如何使用 JavaScript 在父元素的内部 HTML 中插入的图标删除列表标签(或任何其他 HTML 元素)?

How can a list tag(or any other HTML element) be removed using an icon inserted in innerHTML of the parent element by JavaScript?

To-do List

我在这里尝试删除一个任务,它是一个列表元素,最初使用来自 FontAwesome 的 'trash' 图标。我正在尝试弄清楚 如何在创建新任务(列表元素)时添加此图标。除此之外,我还想 在用户单击位于特定列表元素内的图标时删除任务 。 我在这里分享一个 codepen link - https://codepen.io/tsiruot/pen/yLOVyGg

   var list = document.getElementById('task-list');
var btnInput = document.getElementById('submit-btn');

btnInput.addEventListener('click', addlist);

var inputBox = document.getElementById('todo-task');

inputBox.addEventListener('keyup', function(e){
    var keyCode = e.keyCode;
    if(keyCode === 13)
    {
        addlist();
    }
})

function addlist(){
    var newElement = document.createElement('li');
    var inputValue = document.getElementById('todo-task').value;
    if(inputValue !== null && inputValue !==undefined && inputValue !=='')
    {
    newElement.appendChild(document.createTextNode(inputValue));
    list.appendChild(newElement);
    document.getElementById('todo-task').value = '';
    }
    else{
        alert('Please Add valid input value');
    }
}

function createNewNode(){
    var newElement = document.createElement('li');
    var inputValue = document.getElementById('todo-task').value;
    if(inputValue !== null && inputValue !==undefined && inputValue !=='')
    {
    newElement.appendChild(document.createTextNode(inputValue));
    return newElement;
    }
    else{
        alert('Please Add valid input value');
    }
}

var btnUpdate = document.getElementById('btn-update');

btnUpdate.addEventListener('click', function(){
    var firstElement = list.firstElementChild;
    var updatedNode = createNewNode();
    list.replaceChild(updatedNode, firstElement);
    document.getElementById('todo-task').value = '';
});

var btnRemove = document.getElementById('btn-remove');

btnRemove.addEventListener('click', function(){
    var firstElement = list.firstElementChild;
    list.removeChild(firstElement);
});

一般资料:

  • 我建议使用 letconst 而不是 var 作为更好的做法:Differences let, const, var.
  • 始终检查列表中的元素数量以确保您不会尝试删除或替换不存在的元素,我在下面的代码中添加了此类控件。

现在,让我们来回答您的要求。在这些简短的解释之后,您将在下面找到有效的、经过测试的代码:

  • 将垃圾桶图标添加到每个新元素足以创建一个 <i> 元素,添加正确的 class 并将其附加到要附加到列表的新元素。
  • 要使垃圾桶图标删除元素,只需向其添加一个事件侦听器。

我还添加了一些代码,以便添加到列表中的新元素获得唯一 ID。我不知道这是否对你有用,但如果不是,你可以删除它。
解释完了,让我们来看代码:

const list = document.getElementById('task-list');
const btnInput = document.getElementById('submit-btn');
//Variable to keep track of all the elements ever created.
let elementCounter = list.children.length;

btnInput.addEventListener('click', addlist);

const inputBox = document.getElementById('todo-task');

inputBox.addEventListener('keyup', function(e) {
    const keyCode = e.keyCode;
    if(keyCode === 13)
    {
        addlist();
    }
});

function addlist()
{
    const inputValue = document.getElementById('todo-task').value;
    if(inputValue !== null && inputValue !== undefined && inputValue !== '')
    {
        //Moved the creation of the new element here so that it's not created when not necessary.
        const newElement = document.createElement('li');
        //Element for the trash icon.
        const trashIcon = document.createElement('i');
        //Add class to the element.
        trashIcon.className = 'fas fa-trash';
        //Add even listener so that when the element is clicked newElement is removed.
        trashIcon.addEventListener('click', function() {
            list.removeChild(newElement);
        });
        //Add unique ID to the new element.
        newElement.id = 'item' + ++elementCounter;
        newElement.appendChild(document.createTextNode(inputValue));
        newElement.appendChild(trashIcon);
        list.appendChild(newElement);
        document.getElementById('todo-task').value = '';
    }
    else
    {
        alert('Please Add valid input value');
    }
}

function createNewNode()
{
    const inputValue = document.getElementById('todo-task').value;
    if(inputValue !== null && inputValue !== undefined && inputValue !== '')
    {
        //Moved the creation of the new element here so that it's not created when not necessary.
        const newElement = document.createElement('li');
        //Element for the trash icon.
        const trashIcon = document.createElement('i');
        //Add class to the element.
        trashIcon.className = 'fas fa-trash';
        //Add even listener so that when the element is clicked newElement is removed.
        trashIcon.addEventListener('click', function() {
            list.removeChild(newElement);
        });
        //Add unique ID to the new element.
        newElement.id = 'item' + ++elementCounter;
        newElement.appendChild(document.createTextNode(inputValue));
        newElement.appendChild(trashIcon);
        return newElement;
    }
    else
    {
        alert('Please Add valid input value');
        //If the new element was not created, return false.
        return false;
    }
}

const btnUpdate = document.getElementById('btn-update');

btnUpdate.addEventListener('click', function() {
    //Do the following code only if there's at least one element in the list.
    if(list.children.length > 0)
    {
        const firstElement = list.firstElementChild;
        const updatedNode = createNewNode();
        //Do the following code only if the new node was created.
        if(updatedNode != false)
        {
            list.replaceChild(updatedNode, firstElement);
            document.getElementById('todo-task').value = '';
        }
    }
    else
    {
        alert('List is empty');
    }
});

const btnRemove = document.getElementById('btn-remove');

btnRemove.addEventListener('click', function() {
    //Do the following code only if there's at least one element in the list.
    if(list.children.length > 0)
    {
        const firstElement = list.firstElementChild;
        list.removeChild(firstElement);
    }
    else
    {
        alert('List is empty');
    }
});

同样在 HTML 文件中,我删除了列表中已经存在的元素,以便所有元素都由上面的 javascript 代码动态创建,并且事件侦听器存在并正常工作。
希望这就是您要找的,欢迎随时提问。

Here's a Codepen with your solution.

您创建一个新的图标元素并将其附加到您的列表中,并根据需要添加类名和 ID:

function addlist(){
var newElement = document.createElement('li');
var newIcon = document.createElement('i');

var inputValue = document.getElementById('todo-task').value;
if(inputValue !== null && inputValue !==undefined && inputValue !=='')
{
newIcon.classList.add("fas");
newIcon.classList.add("fa-trash");
newIcon.setAttribute("id","icon3");
newElement.appendChild(document.createTextNode(inputValue));
list.appendChild(newElement);
newElement.appendChild(newIcon);
newElement.setAttribute("id","item3");
delButton3 = document.getElementById('icon3');
document.getElementById('todo-task').value = '';
}
else{
    alert('Please Add valid input value');
}

}

然后创建你的节点:

function createNewNode(){
var newElement = document.createElement('li');
var newIcon = document.createElement('i');
newElement.appendChild(document.createTextNode(inputValue));

var inputValue = document.getElementById('todo-task').value;
if(inputValue !== null && inputValue !==undefined && inputValue !=='')
{
    
newElement.appendChild(document.createTextNode(inputValue));
newIcon.classList.add('fas fa-trash');
list.appendChild(newIcon);
return newElement;

}
else{
    alert('Please Add valid input value');
}
var delButton3 = document.getElementById('icon3'); 

}

当找到具有该类名的项目时应应用您的删除功能,因为当页面加载时该元素尚不存在:

document.addEventListener('click',function(e){
if(e.target && e.target.id== 'icon3'){
      console.log('clicked')
      var item3 = document.getElementById('item3');
      item3.parentNode.removeChild(item3);
 }

});

只需查看 codepen 即可获得说明:)