简体   繁体   English

如何从div中删除元素?

[英]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. label“点击”时,成功生成三个标签“一”“二”“三”。

When I click label "one" labels "four" "five" "six" are generated successfully.当我单击 label “一”标签“四”“五”“六”成功生成。

When I again click label "one" "three four five" labels are removed.当我再次单击 label 时,“一”“三四五”标签被删除。

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".但问题是当我点击 label “点击”然后 label “一”.. 现在当我再次点击“一”时,label “一二三”被单独删除,但不是“四五六一二三”。

HTML label elements do not have a clicked attribute so it's not a good idea to give them a clicked property. HTML label 元素没有clicked属性,因此给它们一个clicked属性不是一个好主意。

Labels are meant for form controls that don't have a label or caption, such as radio buttons and checkboxes.标签适用于没有 label 或标题的表单控件,例如单选按钮和复选框。 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. id 属性必须以字母开头,不能全是数字。

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 .我认为您的问题是one创建的标签看起来就像四个创建的标签。 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.使用元素检查器查看发生了什么。

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

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