Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a problem that i want to bind my 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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
172 views
Welcome To Ask or Share your Answers For Others

1 Answer

First of all, you should not pass a string to setTimeout: this is bad practice. 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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...