change img src and width
I change the开发者_开发百科 scr of an img tag using jQuery, such as,
$("#img1").attr("src", "pic1.png");
after this, I try to get the width of img (it's not set in html),
$("#img1").width();
it seems the width is not changed with the src, did I miss something? thanks.
If you're trying to do it immediately, it may be because the image isn't fully loaded yet.
Add a single load handler to the image using .one()
.
$("#img1").attr("src", "pic1.png").one('load',function() {
alert($(this).width());
});
or in case the image was cached, you can try this:
$("#img1").attr("src", "pic1.png").each(function() {
if( this.complete ) {
alert($(this).width());
} else {
$(this).one('load',function() {
alert($(this).width());
});
}
});
As noted by @Humberto, you were using scr
instead of the proper src
.
精彩评论