javascript 无法调用未定义的方法 appendChild

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7246767/
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-10-25 23:26:53  来源:igfitidea点击:

cannot call method appendChild of undefined

javascript

提问by Learner2011

I get this error when I insert a a href tag inside innerHtml in the javascript (flickrshow-7.1.js), for inserting a link for an image. Images are pulled from the flickr account using flickrshow javascript and displayed in the website as slideshow.

当我在 javascript (flickrshow-7.1.js) 的innerHtml 中插入aa href 标签以插入图像链接时出现此错误。图像是使用 flickrshow javascript 从 flickr 帐户中提取的,并作为幻灯片显示在网站上。

a.onLoadWindow = function() {
    a.elements.target = typeof a.elements.target === "string" ? document.getElementById(a.elements.target) : a.elements.target;
    a.elements.target.innerHTML = '<a href="http://www.google.com"><div class="flickrshow-container" style="background:transparent;height:' + a.elements.target.offsetHeight + "px;margin:0;overflow:hidden;padding:0;position:relative;width:" + a.elements.target.offsetWidth + 'px"></div></a>';

回答by JaredPar

The undefinederror means the javascript variable you are tying to call appendChildon doesn't have a value. You need to fix the initialization so it has a value on which to call appendChild

undefined错误意味着您要调用的 javascript 变量appendChild没有值。您需要修复初始化,以便它具有要调用的值appendChild

<p id="parent"></p>

...

var newNode = document.createElement("li");
var parent; 
parent.appendChild(newNode);  // Error!!! What is parent?
parent = document.getElementById("parent");
parent.appendChild(newNode);  

回答by kennebec

An img element has no innerHTML, and you can not append a child node to an img. Wrap the images in the a elements instead.

img 元素没有innerHTML,您不能将子节点附加到img。将图像包装在 a 元素中。