简体   繁体   中英

Javascript setTimeout in onClick

I have small problem with a submit button.. When it's clicked I want it to perform different actions, but two later than the other one. I have been trying to use a setTimeout from Javascript and place some of the actions I want it to perform in a different function, but then my code doesn't work anymore because it doesn't know what 'this' is anymore. Any help please?

 function test(){
    $(this).addClass("voted");
    $(this).val('lighted up');
  }

  $(".stem").click(function() { 
      $(this).parent().parent().parent().find(".red").addClass("filltherm");
      setTimeout(test,1500);
  });

$(this) will be undefined in function test as $(this) refers to the current element whose event has occurred and your function is separate thing, use a variable to store reference of it.

do like this:

var temp;

 $(".stem").click(function() { 
      temp = $(this);
      $(this).parent().parent().parent().find(".red").addClass("filltherm");
      setTimeout(test,1500);
  });


function test(){
    temp.addClass("voted");
    temp.val('lighted up');
  }

Store a reference to this in _this and pass that as a parameter to temp .

function test(el) {
  $(el).addClass("voted");
  $(el).val('lighted up');
}

$(".stem").click(function() { 
  var _this = this;
  $(this).parent().parent().parent().find(".red").addClass("filltherm");
  setTimeout(function () {
    test(_this);
  }), 1500);
});

You need to store a variable holding the value of this :

function test($el){
  $el.addClass("voted");
  $el.val('lighted up');
}

$(".stem").click(function() {
  var $el = $(this);
  $el.parent().parent().parent().find(".red").addClass("filltherm");
  setTimeout(function() {
    test($el);
  }, 1500);
});

您可以使用proxy方法指定什么this应和了函数调用:

setTimeout($.proxy(test, this),1500);

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