简体   繁体   中英

How to remove the element from div?

var aa = 0;
var arr = new Array("one", "two", "three");
var arr1 = new Array("four", "five", "six");

function cl(me) {
    me.clicked = !me.clicked;
    var id = me.id;
    if (me.clicked) {
        if (id == 1000) aa = arr;
        if (id == "one" || id == "two" || id == "three") aa = arr1;
        var s = document.getElementById("sample");
        var d = document.createElement("div");
        d.id = me.id + 1;
        s.appendChild(d);
        for (i = 0; i < aa.length; i++) {
            var l = document.createElement("label");
            l.innerHTML = aa[i];
            l.id = aa[i];
            l.onclick = function (){cl(this)};
            d.appendChild(l);
        }
    } else {
        var child = document.getElementById(me.id + 1);
        var parent = document.getElementById("sample");
        parent.removeChild(child);
    }
}

Markup:

<label id="1000" onclick="cl(this)">click</label><br><div id="sample"></div>

When the label "click" is clicked, three labels "one" "two" "three" are generated successfully.

When I click label "one" labels "four" "five" "six" are generated successfully.

When I again click label "one" "three four five" labels are removed.

But the problem is when I click label "click" and then label "one".. now when i click "one" again the label "one two three" is alone removed but not "four five six".

HTML label elements do not have a clicked attribute so it's not a good idea to give them a clicked property.

Labels are meant for form controls that don't have a label or caption, such as radio buttons and checkboxes. A more appropriate element here would be a button (either a button or input type button element).

Id attributes must start with a letter, they can't be all numbers.

Browsers will tolerate all of the above, however it's not a good idea to ignore specifications because a browser may be released that adheres to the specification in ways your code doesn't.

I think your issue is that the labels created by one look just like the ones created by four . If you remove four by clicking on one , you can't remove the labels it created until you create it again.

Use an element inspector to see what's happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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