簡體   English   中英

document.getElementById()返回null

[英]document.getElementById() returns null

我正在為JS創建一個庫,該庫允許創建,刪除和編輯窗口小部件。 創建新的小部件時,它會自動獲取一個ID,例如“ widget5”或數組中的下一個數字。 刪除后,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);
    }

小部件ID內有一個空格:

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

所選選項的值存儲在value屬性中:

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

您在id中有一個前導空格。

在您的deleteWidget函數中更改:

widget = document.getElementById(widget);

至 :

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

或只是刪除空間

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

在此處修復: http : //codepen.io/theConstructor/pen/XKabpj

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM