2011-11-15 72 views
3

我試圖改變使用一個DIV的內容:如何使用.load和.fadeIn更改DIV內容?

$('#content').click(function() { 
    $('#content').fadeOut().load('about.php').fadeIn('normal'); 
}); 

但它始終閃爍,我不知道如何解決這個問題,因爲我在jQuery的一點點經驗不足。

我在這裏看着這個相同的問題,我試過選擇的答案,但無濟於事。

回答

4

您應該使用.fadeOut()和​​函數的回調函數。目前你正在淡出,添加HTML,然後同時淡入。

嘗試:

//add event handler to click event for the #content element 
$('#content').click(function() { 

    //cache this element 
    var $this = $(this); 

    //fadeOut the element 
    $this.fadeOut(function() { 

     //after fadeOut is done, change it's HTML 
     $this.load('about.php', function() { 

      //now fadeIn the new HTML, this is in the callback for the `.load()` 
      //function because `.load()` is an asynchronous function 
      $this.fadeIn(); 
     }); 
    }); 
}); 


我嵌套所有callback功能的原因是,下一個運行之前每個進程都可以完成。首先允許.fadeOut()完成,然後允許​​獲取數據並將其放置在DOM中,然後我們用.fadeIn()元素與新的HTML。

+0

感謝您的解釋。它解決了我的問題。 – vvhat

+0

我很高興它有幫助。 – Jasper

3

你可能會做這樣的事情:

$('#content').click(function(){ 
    $('#content').fadeOut(function(){ 
    $('#content').load('about.php').fadeIn('normal'); 
    }); 
}); 

使用load作爲callbackfadeOut

+1

Apreciated的答案,謝謝。 10分給你。 – vvhat