Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

javascript - 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>

   

   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I declared "sil" as const and give it a value in every loop again and again.

In udemy course instr?ctor pointed that const values cant be changed, so how could it worked?

Every iteration of the loop creates a new environment so every iteration basically has its own sil variable. You are never assigning a new value to an existing sil variable (which would not work as already mentioned).

"sil.addEventListener" -> How this listeners function deleted the correct list element?

For the same reason: Every iteration has its own sil variable. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...