开发者

How do I pull the value of an attribute as it's being cached in JavaScript?

开发者 https://www.devze.com 2023-02-07 03:06 出处:网络
I am trying to pass along both the src and the rel tag values. Here\'s the sample input. <img class=\"image\" src=\"example.jpg\" title=\"\" rel=\"value\" />

I am trying to pass along both the src and the rel tag values. Here's the sample input.

<img class="image" src="example.jpg" title="" rel="value" />

The following is some code that is parsing all <img> tags on a page.

add: function(src, rel) {
    if (this.cache[src]) {
        return this.cache[src];
    }
        if (this.cache[rel]) {
            return this.cache[rel];
        }
    var image = new Image();
    image.src = src;
        image.rel = rel;
    this.setStyle(image, {display: 'block'});
    if (image.complete && image.width) {
        return image;
    }
    image.onload = (function(scope) {
        return function() {
            scope.cache[src] = image;
        };
    })(this);
        jQuery(image).attr('rel', function() { image.rel } );
    return image;
},

However, this is my output.

<img src="example.jpg" style="dis开发者_如何学Cplay: block;" />

It's as if it's completely ignoring the rel tag. I need to pass the rel tag value from the old <img> to the new <img>.


The code is setting the properties. Not sure, but if the rel property doesn't map to the attribute, it won't show up.

Also jQuery muddles the distinction between attributes and properties a bit, so I'm not sure how it treats rel.

When you're setting the rel, add a setAttribute() call.

var image = new Image();
image.src = src;
image.rel = rel;
image.setAttribute('rel',rel);

Your original code does cause the rel property to be set, but not the attribute. This will actually set the attribute.

You should be able to get rid of this line:

jQuery(image).attr('rel', function() { return image.rel } );

EDIT:

Here's an alternate solution:

It seems that if you first set image.rel = rel;, the jQuery has no effect. Get rid of that line, and the jQuery code will work.

0

精彩评论

暂无评论...
验证码 换一张
取 消