Javascript 将图像对象插入 HTML

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

Insert image object into HTML

javascripthtmlimage

提问by daryl

I'm just curious to know if there's a better solution for doing this:

我只是想知道是否有更好的解决方案:

var img = new Image();
var div = document.getElementById('foo');

img.onload = function() {
  div.innerHTML += '<img src="'+img.src+'" />'; 
};

img.src = 'path/to/image.jpg';

Desired method:

想要的方法:

console.log(img); // <img src="path/to/image.jpg" />
div.innerHTML += img;

Thoughts?

想法?

回答by jfriend00

I think what you want is this:

我想你想要的是这个:

var img = new Image();
var div = document.getElementById('foo');

img.onload = function() {
  div.appendChild(img);
};

img.src = 'path/to/image.jpg';

You already have a loaded image object. You should just append it directly into the DOM rather than create a whole new image object with innerHTML.

您已经有一个加载的图像对象。您应该直接将其附加到 DOM 中,而不是使用innerHTML.

In addition using +=with innerHTMLis very wasteful as it takes all the objects you already have in there, converts them to HTML text, adds onto that text and then makes all new DOM objects - losing all event handlers when it makes new objects too. It's way, way more efficient to just add a new DOM object onto the set of existing DOM object.

此外,使用+=withinnerHTML是非常浪费的,因为它需要您已经拥有的所有对象,将它们转换为 HTML 文本,添加到该文本上,然后创建所有新的 DOM 对象 - 当它也创建新对象时会丢失所有事件处理程序。将一个新的 DOM 对象添加到现有的 DOM 对象集上,这是一种更有效的方式。

In addition, document.getElementById()takes the id without a #in front of it.

另外,document.getElementById()#前面没有a的id 。

回答by Praveen Kumar Purushothaman

You can use this way:

你可以这样使用:

var img = new Image();
var div = document.getElementById('theDiv');

img.onload = function() {
  div.appendChild(img);
};

img.src = 'path/to/image.jpg';