document.getElementById()返回null

时间:2016-07-06 13:56:40

标签: javascript html

我正在为JS编写一个库,允许创建,删除和编辑小部件。当您创建新窗口小部件时,它会自动获取类似“widget5”的ID或者数组中的下一个数字。删除时,document.getElementById()找不到id并返回null。

我意识到有很多关于这个问题的问题,答案通常与页面前的JavaScript加载有关,但由于我正在编写的小部件库在页面加载后添加了小部件,所以不应该是问题。

我认为问题在于,在使用JS创建窗口小部件时,JS由于某种原因无法找到它。例如,如果我在一个小部件中进行硬编码,JS就可以找到id。我该如何解决这个问题?

非常感谢任何帮助!

http://codepen.io/amstrudy/pen/grxpOK

    //this is just the function that is supposed to find the id, check the codepen above for the full code

    function deleteWidget(){
        var widget = document.getElementById("delList");
        widget = widget.options[widget.selectedIndex].text;
        window.alert(widget);
        widget = document.getElementById(widget);
        window.alert(widget);
        document.getElementById("body").removeChild(widget);
    }

3 个答案:

答案 0 :(得分:6)

小部件ID中有一个空格:

div.setAttribute("id", " widget" + widgetNum);
                       ^ here

答案 1 :(得分:0)

所选选项的值存储在value atttribute:

widget = widget.options[widget.selectedIndex].value; // instead of .text

答案 2 :(得分:0)

你在id中有一个领先的空间。

在您的deleteWidget功能更改中

widget = document.getElementById(widget);

to:

widget = document.getElementById(" " + widget);

或只删除空格

div.setAttribute("id", "widget" + widgetNum);

已在此处修复:http://codepen.io/theConstructor/pen/XKabpj

希望这有帮助

相关问题