将图像对象插入HTML [英] Insert image object into HTML
问题描述
var img = new Image() ;
var div = document.getElementById('foo');
img.onload = function(){
div.innerHTML + ='< img src =''+ img.src +'/>';
};
img.src ='path / to / image.jpg';
所需方法:
的console.log(IMG); //< img src =path / to / image.jpg/>
div.innerHTML + = img;
想法?
var img = new Image();
var div = document.getElementById('foo');
img.onload = function(){
div.appendChild(img);
};
img.src ='path / to / image.jpg';
您已经有一个加载的图像对象。您应该直接将其附加到DOM中,而不是使用 innerHTML
创建一个全新的图像对象。 b
$ b
使用 + =
和 innerHTML
是非常浪费的,因为它会将您已经拥有的所有对象都转换为HTML文本,将其添加到该文本中,然后生成所有新的DOM对象 - 在创建新对象时也会丢失所有事件处理程序。另外, document.getElementById()方法可以更有效地将一个新的DOM对象添加到现有的DOM对象集中。
#
的编号。 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?
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
.
In addition using +=
with innerHTML
is 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.
In addition, document.getElementById()
takes the id without a #
in front of it.
这篇关于将图像对象插入HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!