getElementById(...)为空?为什么?

时间:2016-10-13 11:26:27

标签: javascript function methods

请检查此代码,并帮我解决为什么我收到类型错误 document.getElementById(...)为null

function Dropdown(){
    this.core = ['NIS', 'EUR', 'USD'];
    this.check = function(){
        var cho = '<select>';
        for(x in this.core){ 
            cho += '<option value="'+ this.core[x] +'">'+ this.core[x] +'</option>';
        }
        cho += '</select>';
        return cho
    };

}

var obj = new Dropdown();
document.getElementById("demo").innerHTML = obj.check();

在HTML文件上我有:

  <div id="demo">Check Console log</div>

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您需要等到文档准备就绪后再与之交互。

window.onload = function() {
    var obj = new Dropdown();
    document.getElementById("demo").innerHTML = obj.check();
};

答案 1 :(得分:0)

如果您在页面呈现时尝试调用此函数,请在关闭body标记之前放置以下脚本

<script>
// self executing function here
(function() {
   // your page initialization code here
   // the DOM will be available here


function Dropdown(){
    this.core = ['NIS', 'EUR', 'USD'];
    this.check = function(){
        var cho = '<select>';
        for(x in this.core){ 
            cho += '<option value="'+ this.core[x] +'">'+ this.core[x] +'</option>';
        }
        cho += '</select>';
        return cho
    };

}
var obj = new Dropdown();
document.getElementById("demo").innerHTML = obj.check();

})();
</script>