对象没有方法'appendChild'

先生

当我将div发送到在文档片段中创建内容的函数时,将片段附加到div时会出现此错误。

Object column_left has no method 'appendChild' ' 

这是我的代码:

function progress_bar(parent_div){      
    var frag = document.createDocumentFragment();
    var d = document.createElement('div');
        d.className = 'progress_bg';
        d.style.width = '90%';
    frag.appendChild(d);
    parent_div.appendChild(frag);
}

该函数的调用方式如下:

var d = document.getElementById('column_left');
progress_bar(d);    

有谁知道为什么我不能像这样追加?

Zhanger

在调用之前progress_bar(d)#column_left尚不存在,因此尚未d定义。由于要将undefined传递给progress_bar,因此无法对其调用appendChild。

为了解决这个问题,您必须先创建#column_left一个,或者选择一个预先存在的元素,例如document.body

是一个JSFiddle,其中的代码已清除,我这样做是为了将它附加到文档的正文中,并且还设置了实际呈现的内部内容。

如果您想在上进行操作#column_left,则将是这样的:

var el = document.createElement('div');
el.id = 'column_left';
document.body.appendChild(el);
progress_bar(el);    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章