简体   繁体   中英

setinterval not working to change image src

Wondering why the following code will not change my img src. The commented out example works just fine. And the alert triggers every 4 seconds. Replacing the src just wont work inside the set interval function.

$(document).ready(function(){
    $(".samples_1_1").on("click", function(){
        alert('asdf');
        //$(this).attr("src", "../../static/results/samples_1_2.png");
        setInterval(function() {
          alert('alert 1');
          $(this).src("src", "../../static/results/samples_1_2.png");        
        }, 4000);
      });
    });

Firstly, in the second example you're using .src(), which does not exist. Use .attr() as before. Secondly, the $(this) keyword is now inside it's own function, making it undefined. You'll need to specify the element manually using $(".samples_1_1").attr("src", "../../static/results/samples_1_2.png");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM