Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

Problems with javascript settimeout function

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...