简体   繁体   English

setinterval无法更改图像src

[英]setinterval not working to change image src

Wondering why the following code will not change my img src. 想知道为什么以下代码不会更改我的img src。 The commented out example works just fine. 注释掉的示例效果很好。 And the alert triggers every 4 seconds. 警报每4秒触发一次。 Replacing the src just wont work inside the set interval function. 替换src只会在set interval函数内部起作用。

$(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. 首先,在第二个示例中,您使用的.src()不存在。 Use .attr() as before. 像以前一样使用.attr()。 Secondly, the $(this) keyword is now inside it's own function, making it undefined. 其次, $(this)关键字现在位于其自己的函数内,从而使其未定义。 You'll need to specify the element manually using $(".samples_1_1").attr("src", "../../static/results/samples_1_2.png"); 您需要使用$(".samples_1_1").attr("src", "../../static/results/samples_1_2.png");手动指定元素$(".samples_1_1").attr("src", "../../static/results/samples_1_2.png");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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