如何将要附加图像的元素传递到image.onload()函数中

How to pass element to append image to in to the image.onload() function

本文关键字:image onload 函数 元素 图像      更新时间:2023-09-26

我正在编写一个库,该库在包装器元素中创建多个元素,并将所有这些元素及其函数存储在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/