Javascript 将脚本附加到 IE 时“无法获取属性‘appendChild’的值:对象为空或未定义”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7173398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:10:41  来源:igfitidea点击:

"Unable to get value of the property 'appendChild': object is null or undefined" while appending script to IE

javascriptfacebookinternet-explorerdomblogger

提问by user784756

When I try to append the following script to IE, I get this error:

当我尝试将以下脚本附加到 IE 时,出现此错误:

"Error: Unable to get value of the property 'appendChild': object is null or undefined"

“错误:无法获取属性‘appendChild’的值:对象为空或未定义”

It works fine in Chrome, but when testing on IE9 this occurs. Can anyone tell me what the error is?

它在 Chrome 中运行良好,但在 IE9 上测试时会发生这种情况。谁能告诉我错误是什么?

  // create script in document
    var fbScript = document.createElement("script");
    fbScript.type = "text/javascript";

    // make script source the facebook plugin
    fbScript.src = "http://connect.facebook.net/en_US/all.js#xfbml=1";



    // append script to appropriate tab
    document.getElementById('Tab' + tab_counter).appendChild(fbScript);

回答by Saffar

This can happen if your javascript code is running before all parts of HTML are loaded. Try to put this code in a function and fire it on an onload event. or use the more elegant jQuery onload event. It is something like this

如果在加载 HTML 的所有部分之前您的 javascript 代码正在运行,就会发生这种情况。尝试将此代码放在函数中并在 onload 事件上触发它。或者使用更优雅的 jQuery onload 事件。它是这样的

$().ready(function () {
    var fbScript = document.createElement("script");
    fbScript.type = "text/javascript";

    // Make script source the facebook plugin
    fbScript.src = "http://connect.facebook.net/en_US/all.js#xfbml=1";

    // Append script to appropriate tab
    document.getElementById("Tab" + tab_counter).appendChild(fbScript);

});