简体   繁体   English

如何删除 javascript 中的 append 子元素

[英]how to remove the append child element in javascript

<label id="1" >a</label><label id="2" > b </label>

I have two labels created.我创建了两个标签。 When a label is clicked, I create a div element within that I displayed.单击 label 时,我会在其中创建一个div元素。 Now I need to remove the created div element if the label is again clicked.现在,如果再次单击 label,我需要删除创建的div元素。

if (click == 1) {
    var prevWin = document.createElement("div");
    prevWin.id = 1;
    prevWin.innerHTML = outMsg;
    document.body.appendChild(prevWin);
} else {
    var prevWin = document.body.getElementsById(1);
    document.body.removeChild(prevWin);
}

When a label is clicked the div element is created successfully.单击 label 时, div元素创建成功。 But when it is clicked again, the div element is not removed.但是当它再次被点击时, div元素并没有被移除。

function labelOnClick () {
    var divs = this.getElementsByTagName("div");

    if (divs.length) {
        divs[0].parentNode.removeChild(divs[0]);
    } else {
        var div = document.createElement("div");
        div.innerHTML = outMsg;

        this.appendChild(div);
    }
}

ids have got to be unique throughout the DOM; ids在整个 DOM 中必须是唯一的; in your example, it looks like you'll have the label and the div with the same id.在您的示例中,看起来您将拥有 label 和具有相同 ID 的 div。 You could easily append a string to the div id, if you want it to have an id ( div.id = this.id + "_div" ).你可以很容易地 append 一个字符串到div id,如果你希望它有一个 id ( div.id = this.id + "_div" )。

My example wont work if you have more than one div in your label;如果您的 label 中有多个 div,我的示例将不起作用; in which case the ID approach would be best (or use a selector library).在这种情况下,ID 方法将是最好的(或使用选择器库)。

Id's could be approached as follows:可以按如下方式处理 ID:

function labelOnClick () {
    function makeDivId(id) {
        return id + "_div";
    };

    var div = this.getElementById(makeDivId(this.id));

    if (div) {
        div.parentNode.removeChild(div);
    } else {
        div = document.createElement("div");
        div.innerHTML = outMsg;
        div.id = makeDivId(this.id);

        this.appendChild(div);
    }
}

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

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