繁体   English   中英

为什么显示[object HTMLCollection]而不是我创建的元素?

[英]Why is [object HTMLCollection] being displayed instead of the element I created?

在Javascript中,我尝试建立一个新的div。 这就是我添加的div。

html+= "<div>" + concerts + "</div>";

但在我的浏览器中,它显示[object HTMLCollection] div标签应在的位置。

音乐会是预定义的变量。

谁能向我解释我可能无法进行这项工作。 提前致谢。

concerts显然是元素的集合,例如您从getElementsByTagName和类似的元素中获得的元素。 当你做

"<div>" + concerts + "</div>"

...您隐式调用了toString ,因此得到了"[object HTMLElementCollection]"字符串。

如果要将集合中的所有元素放在一个div中,然后将该div添加到页面中,则不能使用字符串concat:

var div = document.createElement('div');
Array.prototype.slice.call(concerts).forEach(concerts, function(concert) {
    div.appendChild(concert);
});
document.body.appendChild(div); // Or wherever you want to add the div

其中的Array.prototype.slice.call(concerts)部分将HTMLElementCollection转换为真正的数组,然后在该数组上使用forEach遍历并将元素移入div. 这个答案进入,在更多的细节。)(我们需要slice的那部分,因为HTMLElementCollections通常是的集合,所以移动第一元素融入DIV需要它的集合,它会搞砸的forEach 。)

本示例以不在div中的四个段落开始。 然后,当您按下按钮时,它将创建一个带有填充和边框的div,并将段落移入其中:

 document.querySelector("button").onclick = function() { var concerts = document.getElementsByTagName("p"); var div = document.createElement('div'); div.className = "foo"; Array.prototype.slice.call(concerts).forEach(function(concert) { div.appendChild(concert); }); document.body.appendChild(div); // Or wherever you want to add the div }; 
 .foo { border: 1px solid black; padding: 4px; } 
 <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> <p>Paragraph 4</p> <button type="button">Click me</button> 

html必须是一个对象。 当您尝试向对象添加内容时,它将变成一个字符串,使其看起来像[object]。 您可能不希望只是+= ,而是在DOM api上使用一种方法来插入演唱会(例如,如果进行了一些更改,例如appendChild可能会起作用)

使用+=您正在向字符串中添加一个对象(似乎是元素的集合),从而导致对其toString()方法的隐式调用。 这样就得到[object HTMLCollection]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM