简体   繁体   English

document.getElementById()返回null

[英]document.getElementById() returns null

I'm writing a library for JS that allows the creation and deletion and editing of widgets. 我正在为JS创建一个库,该库允许创建,删除和编辑窗口小部件。 When you create a new widget, it automatically gets an id like "widget5" or whatever is the next number in the array. 创建新的小部件时,它会自动获取一个ID,例如“ widget5”或数组中的下一个数字。 On deletion, document.getElementById() can't find the id and returns null. 删除后,document.getElementById()找不到ID,并返回null。

I realize there are a lot of questions about this problem, and the answer usually has to do with the JavaScript loading before the page, but since the widget library I am writing adds widgets after the page is loaded, that shouldn't be the problem. 我意识到有关此问题有很多问题,答案通常与页面之前的JavaScript加载有关,但是由于我正在编写的窗口小部件库在页面加载后会添加窗口小部件,所以这不是问题。

I think the problem is that when creating a widget using JS, the JS can't find it for some reason. 我认为问题在于使用JS创建小部件时,JS由于某种原因找不到它。 For example, if I hard-coded in a widget the JS has no problem finding the id. 例如,如果我在小部件中进行了硬编码,则JS可以轻松找到ID。 How can I fix this? 我怎样才能解决这个问题?

Any help is much appreciated! 任何帮助深表感谢!

http://codepen.io/amstrudy/pen/grxpOK 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);
    }

There's a space inside your widget ids: 小部件ID内有一个空格:

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

所选选项的值存储在value属性中:

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

You have a leading space within the id . 您在id中有一个前导空格。

In your deleteWidget function change : 在您的deleteWidget函数中更改:

widget = document.getElementById(widget);

to : 至 :

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

or just remove the space 或只是删除空间

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

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

Hope this helps 希望这可以帮助

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

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