简体   繁体   English

如何使用 JavaScript 插入父元素的 innerHTML 中的图标删除列表标签(或任何其他 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待办事项清单

Here I am trying to delete a task which is a list element originally using the 'trash' icon from FontAwesome.在这里,我试图删除一个任务,该任务最初是使用 FontAwesome 中的“垃圾桶”图标的列表元素。 I am trying to figure out how to add this icon when a new task(list element) is created .我想弄清楚如何在创建新任务(列表元素)时添加此图标 Besides this, i also want to delete a task when a user clicks on the icon positioned inside that particular list element .除此之外,我还想在用户单击位于该特定列表元素内的图标时删除任务 I am sharing a codepen link here - https://codepen.io/tsiruot/pen/yLOVyGg我在这里分享一个 codepen 链接 - 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);
});

General stuff:一般的东西:

  • I suggest to use let and const instead of var as better practice: Differences let, const, var .我建议使用letconst而不是var作为更好的做法: Differences let, const, var
  • Always check for the number of elements in the list to make sure you will not try to delete or replace elements that do not exist, I added such controls in the code below.始终检查列表中的元素数量以确保您不会尝试删除或替换不存在的元素,我在下面的代码中添加了此类控件。

Now, let's come to your requests.现在,让我们来满足您的要求。 After these brief explanation you'll find the working, tested code below:在这些简短的解释之后,您将在下面找到有效的、经过测试的代码:

  • To add the trash icon to every new element is sufficient to create an <i> element, add the correct class and append it to the new element that is being appended to the list.要将垃圾桶图标添加到每个新元素足以创建一个<i>元素,请将正确的 class 和 append 添加到要附加到列表的新元素中。
  • To make the trash icon delete the element just add an event listener to it.要使垃圾桶图标删除元素,只需向其添加一个事件侦听器。

I also added pieces of code so that new elements added to the list get a unique ID.我还添加了一些代码,以便添加到列表中的新元素获得唯一 ID。 I don't know if this may be useful to you, but if it's not you can just remove it.我不知道这是否对您有用,但如果不是,您可以将其删除。
Now enough with the explanations, let's get to the code:现在解释够了,让我们来看看代码:

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');
    }
});

Also in the HTML file I removed the already present elements in the list so that all the elements are dynamically created by the javascript code above and the event listeners are present and work properly.同样在 HTML 文件中,我删除了列表中已经存在的元素,以便所有元素都由上面的 javascript 代码动态创建,并且事件侦听器存在并正常工作。
Hope this is what you were looking for, feel free to ask any question.希望这就是您要找的东西,请随时提出任何问题。

Here's a Codepen with your solution.这是包含您的解决方案的 Codepen。

You create a new icon element and append it to your list, adding classnames and IDs as needed:您创建一个新的图标元素并将其 append 添加到您的列表中,并根据需要添加类名和 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');
}

} }

Then create your node:然后创建你的节点:

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'); 

} }

Your delete function should be applied when the item with that classname is found, since when the page loads that element doesn't exist yet:当找到具有该类名的项目时,应应用删除 function,因为当页面加载时该元素尚不存在:

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

}); });

Just check the codepen for clarification:)只需检查 codepen 即可澄清:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM