简体   繁体   English

javascript settimeout function 的问题

[英]Problems with javascript settimeout function

I have a problem that i want to bind my setTimeout我有一个问题要绑定我的setTimeout

$(document).click(function () {
    function aktivereSkift() {
        $(this).attr("src", "/lib/pictures/picA.png");
        setTimeout("$('.myImg').attr('src', '/lib/pictures/picB.png')", 3000);
    }

    $(".myImg").on("click", aktivereSkift);
});

The problem is that i can only get i to work with this, which is not working properly it changes all the images to picB.png... is there a way that i cant do some "binding" like i do with the first $(this).attr changer??问题是我只能让我使用这个,它不能正常工作它会将所有图像更改为 picB.png ...有没有一种方法我不能像第一个 $ 那样做一些“绑定” (this).attr changer??

First of all, you should not pass a string to setTimeout : this is bad practice.首先,您不应该将字符串传递给setTimeout :这是不好的做法。 Pass a function, and make it an arrow function so that you can still refer to the same this as in the statement before it:传递一个 function,并将其设为箭头 function,以便您仍然可以参考this的语句中的内容:

  function aktivereSkift() {
      $(this).attr("src", "/lib/pictures/picA.png")
      setTimeout(() => $(this).attr('src', '/lib/pictures/picB.png'), 3000);
  }

NB: it is strange that you put your code in a $(document).click handler.注意:将代码放在$(document).click处理程序中很奇怪。

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

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