2014-10-10 46 views
0

我有一個jQuery函數寫在下面。我想在函數中發生的是,.fadeToggle消除不需要的元素,之後選定的div將pod擴展類應用於其自身。由於某種原因,每當我添加setTimeout函數wrapping toggleClass podexpanded toggleClass展開部分不起作用。沒有setTimout函數工作正常,但我需要延遲代碼的第二部分,直到第一部分完成。設置超時不工作在jQuery sequnce

這裏是我的代碼:

jQuery(document).on('click', '.portfoliopod', function(){ 





jQuery('.portfoliopod').not(jQuery(this)).fadeToggle(500); 


setTimeout(function() { 
jQuery(this).toggleClass('podexpanded'); 
    }, 600); 



jQuery(this).toggleClass("portfolioimagezoom"); 


    jQuery(this).children(".portfoliopodmessage").toggleClass('hidepod'); 


setTimeout(function() { 
    jQuery(".portfolioimage").toggleClass('portfolioimagelarge'); 

}, 400); 
}); 
+2

You ca不要在'setTimeout'裏面使用'this'。當函數運行時,'setTimeout'將'this'設置爲'window'。 – 2014-10-10 18:54:30

回答

0

任何的setTimeout調用之前,添加:

var th = jQuery(this); 

然後在超時功能,我們日,而不是jQuery的(這)是這樣的:

th.toggleClass('podexpanded'); 
+0

作品!謝了哥們 – 2014-10-10 19:02:43

-1

fadeToggle的第三個參數允許你以供應fadeToggle的動畫完成後執行的函數。

jQuery(document).on('click', '.portfoliopod', function() 
{ 

    jQuery('.portfoliopod').not(jQuery(this)).fadeToggle(500, 'swing', function() 
    { 
     $(this).toggleClass('podexpanded'); 
    }); 
}); 

$(document).ready(function() 
 
{ 
 

 
    $("#test").hide(); 
 
    
 
    $("#test").fadeToggle(500, 'swing', function() 
 
    { 
 
    $(this).addClass('a_new_class').html('Update to this text after fadein in original div.'); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="test">My text</div>

+0

由於超時不起作用的原因不起作用。在函數內使用「this」是指該函數。 – Brian 2014-10-10 19:02:54

+0

使用$(this)指的是也應用了fadeToggle的原始選擇元素,而不是被調用的函數。在這種情況下絕對沒有理由使用setTimeOut。我添加了一個示例代碼片段。 – Venice 2014-10-10 19:17:36

+0

請參閱我編輯回答的例子。它演示了我所說的完美。 'this'參照調用方法的對象,而不是方法本身。這,我的朋友,是基本的JavaScript。 – Venice 2014-10-10 19:39:58