将图像对象插入HTML [英] Insert image object into HTML

查看:103
本文介绍了将图像对象插入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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆