最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Change <img > image with JavaScript Image object - Stack Overflow

programmeradmin1浏览0评论

I have a JavaScript Image object that I load dynamically with jQuery.

What I want to do is change a <img /> image with one stored on my Image object. How should I do this?

Note: I want to avoid changing the source of my <img /> tag as it downloads it again from the server, and I already have the image stored in my image object

I have a JavaScript Image object that I load dynamically with jQuery.

What I want to do is change a <img /> image with one stored on my Image object. How should I do this?

Note: I want to avoid changing the source of my <img /> tag as it downloads it again from the server, and I already have the image stored in my image object

Share Improve this question asked Mar 10, 2013 at 21:44 PachaPacha 1,5264 gold badges25 silver badges48 bronze badges 4
  • Have you tried $(image)? Images are usually cached, so loading the same image twice won't download it twice. – Blender Commented Mar 10, 2013 at 21:46
  • 1 I don't get it. Could you explain a bit more? I already know what $(image) does, but I have the image stored in a JavaScript Image object, and I want to avoid changing the src as I don't want to download the image every time I change it – Pacha Commented Mar 10, 2013 at 21:47
  • 1 Wrap your image object in the jQuery function. Images are cached, so re-downloading it usually doesn't make a difference. – Blender Commented Mar 10, 2013 at 21:48
  • I think the Image object only stores a reference to the image, not the image it's self. – louisbros Commented Mar 10, 2013 at 21:50
Add a comment  | 

4 Answers 4

Reset to default 11

You mean

$('#imageToChange').replaceWith(imageObject)

?

New Image object:

var Image_off = new Image();
Image_off.src = 'first.jpg';

image src change with jQuery:

$("#my_image").attr("src",Image_off.src);

With jQuery... have both images already on your page and show or hide either one, based on a logical condition.

Make your new image in javascript memory, and then append it after the original image, then remove the original. You may also wish to cache the original before removing it in case you would like to re-use it.

html

<img id="replace" />

js

var img = new Image();
img.src = "someUri.png";
$("#replace").after(img);
$("#replace").remove();
发布评论

评论列表(0)

  1. 暂无评论