简体   繁体   English

如何删除最后(动态)创建的元素?

[英]How to delete elements, which were created last (dynamically)?

So, I have 2 functions, 因此,我有2个功能,

1st one creates 10 elements: 第一个创建10个元素:

    function addDay() {
           // For loop to create 10 div elements. 
           for (k = 1; k < 11; k++) {     
           let div = document.createElement("div");
           div.setAttribute("class", "studentGrades")
           div.className += " sgID" + k
           div.setAttribute("onclick", "userInput(this, Number(prompt('Please, enter 
    number here')))");
           div.innerHTML = "0"
           document.querySelector("#container3").appendChild(div)
           }}

2nd one is used to delete previously genereated elements (div): 第二个用于删除以前生成的元素(div):

 function removeDay() {
 // Looping through all 10 div elements to delete them.
 for (let j = 0; j < 10; j++) {
    let removeDay = document.querySelector('.studentGrades');
    removeDay.parentNode.removeChild(removeDay);
}}

These functions represent buttons (Add Day) and (Remove Day) 这些功能代表按钮(添加日期)和(删除日期)

And here is the problem, Button can be clicked (10times for example) which will create 10 columns, each containing 10 div element, I want my removeDay function to delete the last column, Right now it does exactly the opposite it deletes The column which was created first. 这是问题所在,可以单击Button(例如,单击10次),这将创建10列,每列包含10个div元素,我希望我的removeDay函数删除最后一列,现在它执行与删除列完全相反的操作首先创建。

The problem is that this line is returning the first element: 问题是此行返回第一个元素:

let removeDay = document.querySelector('.studentGrades');

You could get the last element with: 您可以使用以下命令获取最后一个元素:

let removeDay = document.querySelector('.studentGrades:last-child');

However, there's no need to call document.querySelector so many times. 但是,无需多次调用document.querySelector Instead, you can directly access the last element of the container with Node.lastChild : 相反,您可以使用Node.lastChild直接访问容器的最后一个元素:

 const container = document.getElementById('container'); const add = document.getElementById('add'); const remove = document.getElementById('remove'); let index = -1; add.onclick = () => { // Add 10 new elements at the end: const newLastIndex = index + 10; while (index < newLastIndex) { let div = document.createElement('div'); div.className = 'studentGrades'; div.innerHTML = ++index; container.appendChild(div); } remove.disabled = false; }; remove.onclick = () => { // Remove last 10 elements: for (let i = 0; i < 10; ++i) { container.removeChild(container.lastChild); // This will not work in IE: // container.lastChild.remove(); } index -= 10; if (index === -1) { remove.disabled = true; } }; 
 body, button { font-family: monospace; } #container { position: relative; border: 3px solid black; border-right: none; margin-bottom: 10px; } #container:empty { border-top: none; } .studentGrades { position: relative; border-right: 3px solid black; width: 10%; box-sizing: border-box; display: inline-block; text-align: right; padding: 5px; } 
 <div id="container"></div> <button id="add">ADD</button> <button id="remove" disabled>REMOVE</button> 

If you don't need to support IE, instead of using Node.removeChild() : 如果不需要支持IE,则可以使用Node.removeChild()

container.removeChild(container.lastChild);

You could use ChildNode.remove() and do: 您可以使用ChildNode.remove()并执行以下操作:

container.lastChild.remove();

document.querySelector() only finds the first match . document.querySelector() 仅找到第一个匹配项

Instead try using: document.querySelector('.studentGrades:last-child') . 而是尝试使用: document.querySelector('.studentGrades:last-child')

Maybe like this: 也许是这样的:

  function addDay() { for (k = 1; k < 11; k++) { let div = document.createElement("div"); div.setAttribute("class", "studentGrades"); div.className += " sgID" + k; div.setAttribute("onclick", "userInput(this, Number(prompt('Please, enter number here')))"); div.innerHTML = "0"; document.querySelector("#container3").appendChild(div) } } function removeDay() { for (let j = 0; j < 10; j++){ if(document.querySelectorAll(".studentGrades:last-child").length){ document.querySelectorAll(".studentGrades:last-child")[0].remove(); } } } 
 <div id="container3"></div> <input type="button" value="add" onclick="addDay();"> <input type="button" value="remove" onclick="removeDay();"> 

You could create a Stack, like this: 您可以创建一个堆栈,如下所示:

function Stack() {
    let items = [];
    let maxIndex = -1;

    this.isEmpty = () => {
        return maxIndex === -1;
    };

    this.push = (item) => {
        (items.length > ++maxIndex) ? (items[maxIndex] = item) : items.push(item);
    };

    this.pop = () => {
        return (maxIndex >= 0) ? items[maxIndex--] : undefined;
    };

    this.top = () => {
        return (maxIndex >= 0) ? items[maxIndex] : undefined;
    }
}

and then push items whenever you add a div : 然后在添加div时推送项目:

function addDay(S) {
       // For loop to create 10 div elements. 
       for (k = 1; k < 11; k++) {     
       let div = document.createElement("div");
       div.setAttribute("class", "studentGrades")
       div.className += " sgID" + k
       div.setAttribute("onclick", "userInput(this, Number(prompt('Please, enter 
number here')))");
       div.innerHTML = "0";
       document.querySelector("#container3").appendChild(div);
       S.push(div);
       }}

and pop whenever you remove an item, here we are just removing all elements from the stack: 并在您删除项目时弹出,这里我们只是从堆栈中删除所有元素:

function removeDay(S) {
 var itemToRemove;
 while (itemToRemove = S.pop()) itemToRemove.remove();
}}

Naturally, somewhere you will need to create the stack somehow, like: 自然地,您将需要以某种方式创建堆栈,例如:

let S = new Stack();

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

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