0

Say my page has loaded successfully. There is an img element in the document like this:

<div class="pro_list_imgbox">
    <img src="http://XXXX.com/bazinga.jpg" />
</div>

And I have backbone.js code like this:

events: {
        'click .pro_list_imgbox': 'loadPic',
    },

loadPic: function (e) {
        var target = $(e.target),
            pic = target[0].nodeName === 'IMG' ? target : target.find('img');

        if (!pic.data('loadState')) {
            pic.attr('src', pic[0].src += '?t' + new Date().getTime());
        }

    },

My question is how can I re-render this img element after I clicked it? Will my loadPic function works? with a random num as suffix of src And maybe something else I should do?

Tamud Gu
  • 31
  • 6
  • Where did you image go after its clicked? Why would you need a random number at the tail of the image source? – seebiscuit Dec 30 '14 at 01:32
  • @Seebiscuit My code is to solve a problem: when the img loading failure,if I click that img,loading the same img again. – Tamud Gu Dec 30 '14 at 01:48
  • OK. Why the random number suffix? – seebiscuit Dec 30 '14 at 01:50
  • @Seebiscuit I tried to add a random number after the source url and see will the browser request and re-render the img(It seems this solution not work).So I'm here to ask how can I re-render the img element by backbone.js or native javascript without another ajax request. – Tamud Gu Dec 30 '14 at 02:03
  • If the image didn't render the first time it probably has to be re-fetched from the server. I would remove the `` element from the DOM and reinsert it. Would you like me to show you how? This will cause another fetch. – seebiscuit Dec 30 '14 at 02:06
  • @Seebiscuit My code is already meet my request.With a random num or time stamp as suffix of src,browser will request the img again without any ajax code which you should have written.[this](http://stackoverflow.com/questions/1997901/how-to-refresh-the-src-of-img-with-jquery) may explained much more clearly – Tamud Gu Dec 30 '14 at 07:49

1 Answers1

0

Looks like you're retrieving your image from a back-end controller, and that image is tagged according to the DateTime recorded upon retrieval.

To retrieve the same image, you'd have to save the source you used to retrieve that image. Given the code you already have, I'd say the most immediate answer would be to store the image source in the <img> element for the image, using $.data(), like this

loadPic: function (e) {
  var target = $(e.target),
  pic = target[0].nodeName === 'IMG' ? target : target.find('img');

  if (!pic.data('loadState')) {
    var picSource = pic[0].src += '?t' + new Date().getTime();
    pic.data({ source: picSource });
    pic.attr('src', picSource);
  }
}

The <img> element that was clicked will now have the last source string for that image and can be recalled using

var imageSource = $('img-selector').data(source);
seebiscuit
  • 4,905
  • 5
  • 31
  • 47