jquery change event when image src changes

后端 未结 4 446
再見小時候
再見小時候 2020-12-05 17:56
$(\'img.product_image\').attr(\'src\').change(function() {
    alert($(\'img.product_image\').attr(\'src\'));
});

Hi ya\'ll

I am trying to

相关标签:
4条回答
  • 2020-12-05 18:47

    You can use .load event in this case:

    $('img.product_image').on('load', function () {
     alert($('img.product_image').attr('src'));
    });
    
    0 讨论(0)
  • 2020-12-05 18:49

    This code should work more reliably than answers that use 'load':

    // ensures this works for some older browsers
    MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
    
    // the element you want to observe. change the selector to fit your use case
    var img = document.querySelector('img.product_image')
    
    new MutationObserver(function onSrcChange(){
      // src attribute just changed!!! put code here
      alert($('img.product_image').attr('src'))
    })
      .observe(img,{attributes:true,attributeFilter:["src"]})
    

    While some answers that use the 'load' event may work most of the time, the load event fires after the 'src' finishes downloading. That event may be delayed if the download takes a while or it may never fire if there is an issue downloading (which happens if the image times out or when you set src to an image that doesn't exist or is invalid, like an empty string ).

    BTW jQuery isnt required but if you really want to use it you can get the target img element like so:

    var img = $('img.product_image').get(0)
    
    0 讨论(0)
  • 2020-12-05 18:52

    You could make use of load event if you like

    $("img.product_image").load(function(){
         alert("New image loaded");
    });
    

    Jsfiddle here

    0 讨论(0)
  • 2020-12-05 18:58

    If I understood your question right, try this:

    Let's say your HTML is something like this:

    <img class="product_image" src="first.png">
    

    You can get the attr() with jQuery like this:

    $(".product_image").attr("src","second.png");
    

    and then using your buttons you load a click function like:

    $('yourButtons').click(function() {
        $('.product_image').attr('src','second.jpg');
    });
    
    0 讨论(0)
提交回复
热议问题