试图在一个元素中创建一个元素。这是 anchor 标记内的 img。 我正在使用 append child 但注销时的“userLogoElement”只是 img 标签,而 anchor 是一个空的 anchor 标签。为什么什么都没有发生?
var anchor = document.createElement('a');
anchor.href = var0;
//---- Create image element ----
var img = document.createElement('img');
img.src = var1;
img.title = var2;
//---- Combine elements ----
var userLogoElement = anchor.appendChild(img);
console.log(userLogoElement, anchor, img);
//console says img === userLogoElement, anchor is empty
最佳答案
代码工作正常 http://jsfiddle.net/gcamP/
注意Node.appendChild()
返回对附加节点的引用,而不是您附加到的节点。这就是为什么 userLogoElement
是图像而不是 anchor 。
另请注意:在 Firebug 中,日志仅显示父 anchor ,控制台日志中不包含其子 anchor 。另一方面,Chrome 确实显示了它。一种简单的测试方法是将其附加到文档中并亲自查看(就像在 fiddle 中一样)。
关于javascript - 嵌套元素创建不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22667327/