簡體   English   中英

Javascript .setTimeout()如何引用一個函數

[英]Javascript .setTimeout() how to refer to a function

我有這些代碼:

$(function(){
    $('.btn').click(function(){
        $title = $(this).attr('title');
        $.get('getOutput', {}, function(){
            // success ajax get                
            // how to refer again to this function? Doing again the $('.btn').click event
            setTimeout(// $('.btn').click(), 100);
        });
    });
})

我想重復按鈕的click事件。 但我的主要問題是,你如何在setTimeout()引用正確的函數或事件?

您可以將其包裝到匿名函數中。

setTimeout(function() {
    $('.btn').click();
}, 100);

如果您想要在之前單擊的特定元素中觸發事件,則需要將當前元素存儲在變量中,因為匿名函數中的this值將不同。

$('.btn').click(function() {
    var $el = $(this);
    // ...your code...
    setTimeout(function() {
        $el.click();
    }, 100);
});

你可以在匿名函數中包含超時回調,然后真正調用那里的click函數。

setTimeout(function() { 
    $(".btn").click(); 
}, 100);

您可以使用$.proxy()在匿名函數中綁定this以與IE8兼容,或者使用.bind()用於現代瀏覽器。

setTimeout($.proxy(function(){
    // this.click(); // if this = $(".btn")
}, this), 100);

要正確解釋:

$(function(){
    var btn = $('.btn');

    btn.click(function(ev){
        var el = $(ev.currentTarget), // same as $(this) but too many "thisses" can be confusing ^^
            title = el.prop('title');

        $.get('getOutput', {}, function(){
            // success ajax get
            // how to refer again to this function? Doing again the $('.btn').click event
            setTimeout($.proxy(function(){
                this.click();
            }, el), 100);
        });
    });
});

您可能最好在命名click事件處理函數並從setTimeout再次調用它,而不是再次觸發click事件。

var handleButtonClick = function() {
    $title = $(this).attr('title');
    $.get('getOutput', {}, function() {
        // success ajax get    
        setTimeout(handleButtonClick , 100);
    });
};

$(function() {
    $('.btn').click(handleButtonClick);
});

暫無
暫無

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

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