简体   繁体   English

(JS 事件委托)如何删除目标元素?

[英](JS event delegation )How can I remove targeted element?

I am struggling with event delegation for a week now.我现在正在为事件委托苦苦挣扎一个星期。

I am trying to remove 'li' element when 'delete' button clicked.单击“删除”按钮时,我试图删除“li”元素。 so far, I have managed to work, however the problem behind that is, all 'li' items are deleted when I just want a single targeted 'li' to be deleted.到目前为止,我已经设法工作,但是背后的问题是,当我只想删除一个目标“li”时,所有“li”项目都被删除了。

How can I fix this code?如何修复此代码?

''' '''

//HTML code for ul and li
        <div>
            <ul id="list">
            </ul> 
        </div>

    //JS code adding inner HTML code for 'edit', 'update' and 'delete' buttons
    document.querySelector(".Add").addEventListener("click", function(){
        data.date.push(date.value);
        data.hours.push(hours.value);  
        const addHTML = `<li><strong>${data.date[i]}</strong> You have worked ${data.hours[i]} hours</li><button class="edit">Edit</button><button class="update">Update</button><button class="delete">Delete</button>`
        document.querySelector('ul').insertAdjacentHTML('afterbegin', addHTML);
        i++;
    });
    
    //JS code to delete the 'li' element when 'delete' button clicked
    document.getElementById('list').addEventListener('click', function(e) {
        const tgt = e.target;
        const parent = tgt.closest('li');
    
        if(tgt.classList.contains('edit')){
            console.log('edit')
    
        }    
        if(tgt.classList.contains('update')){
        console.log('update')
        }  
        if(tgt.classList.contains('delete')){
            console.log(tgt.closest('li'))
            tgt.parentNode.remove();
        }
    });

'''

wait... after putting more effort, I got the answer, So when I added HTML code using 'insertAdjacentHTML'.等等...经过更多努力,我得到了答案,所以当我使用“insertAdjacentHTML”添加 HTML 代码时。 I nested the HTML coded added with element.我嵌套了 HTML 编码添加元素。

Now when I click the targeted button, it will delete the parent element which is现在,当我单击目标按钮时,它将删除父元素

Hope this helps anyone struggling with the same issue.希望这可以帮助任何在同样问题上苦苦挣扎的人。

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

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