简体   繁体   English

将事件侦听器添加到 <li> 使用javascript创建的

[英]Adding event listeners to <li> that are created using javascript

I am quite new to manipulating elements in the DOM in JS so I am creating a simple to do list to get more comfortable and where I can add items using the input and remove items by clicking on the list item. 我对在JS中处理DOM中的元素非常陌生,因此我正在创建一个简单的待办事项列表,以使其更加舒适,并且可以在其中使用输入来添加项目,并通过单击列表项来删除项目。 ALthough this may not be best practice and limitting I am just wanting to use create and remove elements rather than using objects or classes until I get more familar, also using plain/vanilla js so please keep this in mind when answering. 尽管这可能不是最佳实践,但我只是想使用create和remove元素,而不是使用对象或类,直到我变得更熟悉为止,也要使用普通/香草js,因此在回答时请记住这一点。

I am trying to add a click event which removes the <li> when the <li> is clicked. 我想添加一个点击事件,删除<li>的当<li>点击。

My logic is... When the page is loaded I can't just run a for loop over all of the <li> s and add event handlers as all of the <li> 's do not exist yet. 我的逻辑是...加载页面后,我不能仅对所有<li>进行for循环并添加事件处理程序,因为所有<li>都不存在。 So my attempted solution is when the addTaskButton event is triggered, we get all of the <li> that are on the page at the time of the event, we loop through all of them and add an eventlistener to <li> 's that are waiting to be removed when clicked. 因此,我尝试的解决方案是触发addTaskButton事件时,我们获得事件发生时页面上的所有<li> ,我们遍历所有这些事件,并向<li>添加一个eventlistener等待点击时被删除。

This doesn't seem to work and may be overly complicated. 这似乎不起作用,并且可能过于复杂。

Can someone please explan to me very simply like I'm 5 why this doesn't work or what a better way to do this would be? 有人可以像我5岁时那样简单地向我解释一下,为什么这不起作用,或者有什么更好的方法可以做到这一点?

Thank you in advance 先感谢您

HTML 的HTML

<ul id="taskList">
    <li>example</li>

</ul>
<input type="text" id="addTaskInput">
<button id="addTaskButton">Add Task</button>

JavaScript 的JavaScript

const taskList = document.querySelector("#taskList");
const addTaskInput = document.querySelector("#addTaskInput");
const addTaskButton = document.querySelector("#addTaskButton");
let taskItem = document.querySelectorAll("li");


addTaskButton.addEventListener("click", () => {
    let taskItem = document.createElement("li");
    taskItem.textContent = addTaskInput.value;
    for (let i = 0; i < taskItem.length; i++) {     
        taskItem[i].addEventListener("click", () => {
            let taskItem = document.querySelectorAll("li");
            taskList.removeChild(taskItem[i]);      
        });
    }
    taskList.appendChild(taskItem);
    addTaskInput.value = " ";
});

Here is code i created for your requirement, this implement jQuery $(document).on mechanism in vanilla javascript, now where ever you create an li inside the document, on clicking that li it will be removed. 这是我根据您的要求创建的代码,此代码在香草javascript中实现了jQuery $(document).on机制,现在您在文档内创建li的任何位置,单击li都会将其删除。

Explaination 讲解

What it does is on clicking the document it checks on which element is clicked (e.target is the clicked element, e is is the click event on document), then checks if the clicked item is an li tag (e.target.tagName will tell us the tag name if the item clicked), so if it is an li just remove it; 它要做的是单击文档,检查要单击哪个元素(例如,target是被单击的元素,e是文档上的单击事件),然后检查被单击的项目是否是li标签(e.target.tagName)如果单击该项目,则会告诉我们标签名称),因此,如果是li,则将其删除;

  const taskList = document.querySelector("#taskList"); const addTaskInput = document.querySelector("#addTaskInput"); const addTaskButton = document.querySelector("#addTaskButton"); addTaskButton.addEventListener("click", () => { let taskItem = document.createElement("li"); taskItem.textContent = addTaskInput.value; taskList.appendChild(taskItem); addTaskInput.value = " "; }); document.onclick = function(e) { if(e.target.tagName == 'LI'){ e.target.remove(); } } 
 <ul id="taskList"> <li>example</li> </ul> <input type="text" id="addTaskInput"> <button id="addTaskButton">Add Task</button> 

Update your for loop like so: 像这样更新您的for循环:

for (let i = 0; i < taskItems.length; i++) {     
    taskItems[i].addEventListener("click", () => 
        taskList.removeChild(taskItems[i]);      
    });
}

Also your initial taskItem variable should be taskItems and is reflected in the for loop above. 同样,您的初始taskItem变量应该是taskItems,并反映在上面的for循环中。

taskList.addEventListener("click", (event) => {
     event.target.remove();
});

When the specified event occurs the event object is returned. 当指定的事件发生时,将返回事件对象。 The event object has several properties, one of them being target which is the element which is the element which the event occured on. 事件对象具有多个属性,其中之一是目标,即作为发生事件的元素的元素。 event.target is returned to us and we are applying the remove() method to event.target event.target返回给我们,我们将remove()方法应用于event.target

because of event "bubbling" or "Event Propagation", we can attach the event handler to an ancestor. 由于事件“冒泡”或“事件传播”,我们可以将事件处理程序附加到祖先。 It's best to attach the event listener to the closest ancestor element that is always going to be in the DOM (won't be removed). 最好将事件侦听器附加到总是在DOM中的最接近的祖先元素(不会被删除)。

When an event is triggered-in this case the "click" event. 触发事件时(在这种情况下为“点击”事件)。 All decending elements will be removed - which in our case as there are only <li> 's this would be fine. 所有下降的元素都将被删除-在我们的例子中,因为只有<li> ,所以就可以了。 But we should be more specific as in a different case we could be attaching this event handler to a div which has several different elements. 但是我们应该更加具体,因为在不同情况下,我们可以将此事件处理程序附加到具有几个不同元素的div上。

To do this we add an if condition to check that the tagName is an <li> 为此,我们添加一个if条件来检查tagName是<li>

if (event.target.tagName == "LI") 

note that the element must be calpitalised 请注意,必须对元素进行校准

Solution is as follows 解决方法如下

taskList.addEventListener("click", (event) => {

      if(event.target.tagName == "LI"){
         event.target.remove();
    }});

Further reading: 进一步阅读:

Event object and its properties: https://developer.mozilla.org/en-US/docs/Web/API/Event 事件对象及其属性: https : //developer.mozilla.org/en-US/docs/Web/API/Event

Event Bubbling: https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles 事件冒泡: https//developer.mozilla.org/zh-CN/docs/Web/API/Event/bubbles

tagName: https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName tagName: https : //developer.mozilla.org/zh-CN/docs/Web/API/Element/tagName

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

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