replace img src with jquery on click

走远了吗. 提交于 2019-12-24 19:16:36

问题


This might seem as child play, but I can't figure out how I can replace the src attribute of an image.

The src is "build.php" which generate the image. What I want is when I click on "mix" it will run build.php to generate a new image, remove the old image and display the new image with a nice fadeout/fadein.

Also with an "Building new image" which hides when the new image is done loading.

I tried with

$("#mix").click(function(){
   var img = new Image();
      $(img).load(function () {
         $(this).hide();
         $('#loader').removeClass('loading').append(this);
         $(this).fadeIn();
   }).attr('src', 'build.php');
});

But the 2nd time I click on "mix" it will place new image under the old image, not remove the old image.


回答1:


$("#mix").click(function(){
       var img = new Image();
          $(img).load(function () {
             $(this).hide();
             $('#loader').removeClass('loading').append(this);
             $(this).fadeIn();
       }).attr('src','').attr('src', 'build.php');
    });

Look below - works :

$(document).ready(function() {
$("#yourimagediv").click(function() {
$("#yourimagediv").attr("src","image.php?"+new Date().getTime());
});
});​
<img id="yourimagediv" src="image.php" />



回答2:


var mix = $('#mix'),
    jqImage = $('#brick-image');

mix.on('click', function (e) {
    var img = new Image();
    jqImage.fadeOut();
    img.onload = function () {
      jqImage.attr('src', img.src);
      jqImage.fadeIn();
    };
    // add param to prevent caching of build.php image
    img.src = 'build.php?' + new Date().getTime();
    e.preventDefault();
});


来源:https://stackoverflow.com/questions/12476646/replace-img-src-with-jquery-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!