簡體   English   中英

onClick中的Javascript setTimeout

[英]Javascript setTimeout in onClick

我有一個提交按鈕的小問題。當它被點擊時,我希望它執行不同的動作,但比其他動作晚兩個。 我一直在嘗試使用來自Javascript的setTimeout並將我希望它執行的一些操作放在不同的函數中,但后來我的代碼不再起作用了,因為它不知道'this'是什么了。 有什么幫助嗎?

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

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

$(this)將在函數測試中undefined ,因為$(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');
  }

_this存儲this_this ,並將其作為參數傳遞給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);
});

你需要存儲一個變量保存的值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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM