[英]How the browser know which one to delete?
var b=0 const btn = document.getElementById(`add`); btn.addEventListener(`click`, function(){ b++; console.log(b) for (let i = b; i <= b; i++) { var num = i.toString(); var yazi = document.getElementById("yazi").value; const li = document.createElement("li"); li.className = `todos${num}`; li.innerHTML = `<div id= "yazii">${yazi}</div><div id="sil"><button class="x" id="x${num}">X</button> </div>`; document.getElementById("todo").appendChild(li); console.log(yazi); const sil = document.getElementById(`x${num}`); console.log(sil); sil.addEventListener(`click`, function(){ console.log(sil); sil.parentElement.parentElement.remove(); }) } });
<div class="container"> <div class="todoheader">To-Do List <div id="sag"><input type="text" id="yazi"><button id="add">Add</button></div></div> <div class="todocontainer"> <ul id="todo"> </ul> </div> </div>
Im learning beginner javascript as a hobby.我学习初学者 javascript 作为爱好。 Tried to create a simple to-do list.
试图创建一个简单的待办事项列表。 It worked but after i reviewed the code, i cant understand why and how it worked.
它起作用了,但是在我查看了代码之后,我无法理解它为什么以及如何起作用。 I declared "sil" as const and give it a value in every loop again and again.
我将“sil”声明为 const,并在每个循环中一次又一次地给它一个值。
1-In udemy course instrıctor pointed that const values cant be changed, so how could it worked? 1-在 udemy 课程中,讲师指出 const 值无法更改,那么它是如何工作的?
2- "sil.addEventListener" -> How this listeners function deleted the correct list element? 2-“sil.addEventListener”->这个监听器function如何删除正确的列表元素?
I declared "sil" as const and give it a value in every loop again and again.
我将“sil”声明为 const,并在每个循环中一次又一次地给它一个值。
In udemy course instrıctor pointed that const values cant be changed, so how could it worked?
在 udemy 课程中,instrıctor 指出 const 值无法更改,那么它是如何工作的呢?
Every iteration of the loop creates a new environment so every iteration basically has its own sil
variable.循环的每次迭代都会创建一个新环境,因此每次迭代基本上都有自己的
sil
变量。 You are never assigning a new value to an existing sil
variable (which would not work as already mentioned).您永远不会为现有的
sil
变量分配新值(如前所述,这将不起作用)。
"sil.addEventListener" -> How this listeners function deleted the correct list element?
"sil.addEventListener" -> 这个监听器function怎么删除了正确的列表元素?
For the same reason: Every iteration has its own sil
variable.出于同样的原因:每次迭代都有自己的
sil
变量。 In each iteration a new event handler is created which has access to that variable.在每次迭代中,都会创建一个可以访问该变量的新事件处理程序。 The variable holds a reference to the element processed in that iteration of the loop.
该变量保存对在该循环迭代中处理的元素的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.