[英]Adding Javascript objects into innerHTML
Say I create an image object like below.假设我创建了一个图像 object,如下所示。 ( create();
is a function I wrote but I know this function works.) ( create();
是我写的 function 但我知道这个 function 有效。)
var img = create("img", "images/duba.jpg");
When I try to put this image into the innerHTML
of another object that's a div, I get this plain text where the image should show up:当我尝试将此图像放入另一个 div 的 object 的innerHTML
中时,我得到了应该显示图像的纯文本:
[object HTMLImageElement]
What's the correct method to insert one object into another like this?像这样将一个 object 插入另一个的正确方法是什么? I have to think there's a more graceful method than hard-coding the innerHTML with strings, which I've tried successfully.我不得不认为有一种比用字符串硬编码 innerHTML 更优雅的方法,我已经成功地尝试过。
Call appendChild
to append the DOM element to an existing element.调用appendChild
到 append DOM 元素到现有元素。
You should use DOM manipulation methods.您应该使用 DOM 操作方法。 Eg例如
I think you need to use:我认为你需要使用:
otherObject.appendChild(img);
If you are creating an element you can't set it as a node's innerHTML, that takes a string of HTML.如果您正在创建一个元素,则不能将其设置为节点的 innerHTML,它采用 HTML 字符串。 Just use DOM manipulation只需使用 DOM 操作
parent.appendChild ( create("img", "images/duba.jpg") );
Use the appendChild
method.使用appendChild
方法。 The innerHTML
property receives a string, not a DOM element. innerHTML
属性接收一个字符串,而不是一个 DOM 元素。
https://developer.mozilla.org/En/DOM/Node.appendChild https://developer.mozilla.org/En/DOM/Node.appendChild
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.