【问题标题】:appendChild to list element is only affecting the last element of list.appendChild 到列表元素只影响列表的最后一个元素。
【发布时间】:2014-05-10 15:42:54
【问题描述】:

我在本地存储中有几个想要在屏幕上显示的元素,我通过遍历列表并使用 javascript 创建元素然后附加它们来实现这一点,除了我的按钮之外,这工作正常am added 仅被添加到最终元素。我似乎无法弄清楚为什么。我可以将其他文本附加到同一个 li 元素,但不能附加到按钮。

感谢任何帮助,谢谢!

document.getElementById('savedScenarios').appendChild(listSavedScenarios());
        function listSavedScenarios() {
            // Create the list element:
            var listElement = document.createElement('ul');
            var button = document.createElement("BUTTON");
            button.setAttribute("id", "load");
            var t = document.createTextNode("CLICK ME");
            button.appendChild(t);
            for(var i = 0; i < localStorage.length; i++) {
                // Create the list item:
                var listItem = document.createElement('li');
                //Get the local storage name and add it to the list elmt
                listItem.appendChild(document.createTextNode(localStorage.key(i)));
                listItem.appendChild(button);
                //update list
                listElement.appendChild(listItem);
            }
            return listElement;
        }

上面的结果是:

li - 来自存储的密钥(1) li - 存储中的密钥(2) li - 存储中的密钥(3) 点击我

【问题讨论】:

    标签: javascript html web local-storage


    【解决方案1】:

    除了我添加的按钮只添加到最终元素。

    不,它 添加到循环中的每个元素中 - 当发生这种情况时,它当然是从当时可能的任何地方获取的,因为 @987654323 就是这样@ 有效 - 它从当前 DOM 位置移除一个元素,然后将该元素附加到其他位置。

    Interface Node, Method appendchild:

    “将节点 newChild 添加到该节点的子节点列表的末尾。如果 newChild 已经在树中,则首先将其移除。”

    你要么必须创建一个新按钮来追加到当前 LIin 你的循环 - 或者至少 clone 元素并将克隆追加到当前 LI。

    (而且您每次都必须为按钮指定不同的 id,因为 id 在文档中必须是唯一的。)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2010-11-13
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 2022-01-07
    • 2018-03-10
    相关资源
    最近更新 更多