如何将要附加图像的元素传递到image.onload()函数中
How to pass element to append image to in to the image.onload() function
我正在编写一个库,该库在包装器元素中创建多个元素,并将所有这些元素及其函数存储在JavaScript对象中。我试图避免ID,因为一个页面上可能有多个该对象的实例。我有一个允许用户更改某些元素的功能,我需要帮助弄清楚如何附加图像。
以下是功能:
foo.prototype.rebrand = function(line1, line2, imgUrl){
this.branding.childNodes[1].innerHTML = line1;
this.branding.childNodes[2].innerHTML = line2;
var brandImage = document.createElement('img');
brandImage.onload = function(){
this.branding.childNodes[0].appendChild(brandImage);
//this won't work
}
brandImage.src = imgUrl;
}
您可以调用foo.rebrand('hello', 'world', 'example.png')
不幸的是,在.onload
函数内部,this
将引用图像元素本身。那么,如何将this.branding.childNodes[0]
传递到图像加载?
如果我这样写函数:
brandImage.onload = function(anything){
this.branding.childNodes[0].appendChild(brandImage);
//this won't work
}
则CCD_ 5将只是对CCD_ 6事件的引用。
编辑以添加jsFiddle:http://jsfiddle.net/KtJd6/
您需要更改引用特定元素的方式来检索元素,而不是子节点。这将使它更加健壮。而且,当您这样做时,您也不需要onload
处理程序中的引用this
。
foo.prototype.rebrand = function(line1, line2, imgUrl){
var brandImage = document.createElement('img');
// find child divs
var divs = this.branding.getElementsByTagName("div");
divs[0].innerHTML = line1;
divs[1].innerHTML = line2;
brandImage.onload = function(){
divs[0].appendChild(brandImage);
};
brandImage.src = imgUrl;
};
注意,我得到的元素是getElementsByTagName()
,而不是引用直接的childNode
索引。这使得它对文本节点的位置不敏感,并且是引用要定位和修改的元素的更稳健的方式。
你可以在这里看到它的工作原理:http://jsfiddle.net/jfriend00/kkXCg/
相关文章:
- image.onload事件和浏览器缓存
- 预加载图像image.onload脚本MVC
- Image.onLoad作用域在JavaScript类中
- Image.onload 函数为高度和宽度返回零
- image.onload() 或 image.addEventListener() 在 Safari 中不起作用,任何解
- HTML5 Canvas:通过 Image.prototype 创建一个 Image.onload() 函数
- jQuery image.onload phantom event firing
- 如何将要附加图像的元素传递到image.onload()函数中
- image.onLoad -- 在触发之前,我应该如何保持数据可用
- image.onload加载到方法中
- 将值从image.onload传递给周围的函数
- image.onload在图像完全加载之前启动
- Opera 和 Safari 不会触发 image.onload
- JavaScript Image onload未被调用
- 对象属性上的Image onload调用
- 为什么当我尝试在画布上创建一个新图像时,没有image onload触发?
- 使用each和image.onload保持数组的顺序
- 无法在image.onload中产生输出
- Safari image.onload事件未使用Blob url启动
- Javascript image.onload on multiple image only working for t