2010-03-07 31 views
1

功能checkSession(){ $就({URL: 「session.php文件」,成功:功能(數據){ 如果(數據== 1){ VAR postFilen = 'msg.php'; $ 。 post(postFilen,function(data){(「。msg」).html(data).find(「。message2」)。fadeIn(「slow」) } else { $('。msg')。隱藏();} }}); // setInterval的( 'checkSession()',1000);何處放置超時()淡出?

現在我想將它已被證明在5秒鐘後淡出。味精 我該怎麼辦做到這一點.. 我曾嘗試過:

function checkSession(){ 
    $.ajax({url: "session.php", success: function(data){ 
     if(data == 1){ 
      var postFilen = 'msg.php'; 
      $.post(postFilen, function(data){ 
      $(".msg").html(data).find(".message2").fadeIn("slow") 
        setTimeout(function() { 
    $('.msg').fadeOut('slow'); 
     }, 5000); 
      }); 
     }else{ 
      $('.msg').hide(); 
     } 
    }}); 
// setInterval('checkSession()',1000); 
} 

但隨後第1次後,不會出現該消息..

回答

2

嘗試與delay方法工作:http://api.jquery.com/delay/

$('#foo').slideUp(300).delay(800).fadeIn(400); 

我你的情況,是這樣的:

$(".msg") 
    .html(data) 
    .find(".message2") 
    .fadeIn("slow") 
    .parent('.msg') 
    .delay(5000) 
    .fadeOut('slow') 

[編輯:修正範例]

[EDIT2:新的範例]


這一個似乎做工精細這裏:

<div class="msg"></div> 
<p> 
    Some text <br /> <a id="bloup" href="">show message</a> 
</p> 

然後

$(function() { 
     $("#bloup").click(function(e) { 
      e.preventDefault(); 

      var data = "<span class='message2'>Hello world</span>"; 

      $(".msg") 
       .show() 
       .html(data) 
       .find('.message2') 
       .fadeIn('slow') 
       .parent('.msg') 
       .delay(2000).fadeOut('slow'); 
     }) 
    }); 
+0

沒有工作..第一次它淡出同時它要顯示,然後第二個和其餘的時間它沒有出現 – Karem 2010-03-07 09:55:35

+0

正確,父母和延遲倒置。修正了我的例子。 – 2010-03-07 11:30:14

+0

+1很好的使用'delay'。 – 2010-03-07 13:04:11

0

先試着寫乾淨的代碼爲我們瞭解您的問題更好,您的$.post的回調函數缺少});這些字符在其上的第一個片段的末尾,並且縮進是不好的第二。

然後查看這些鏈接以瞭解setTimeout的使用。

https://developer.mozilla.org/en/DOM/window.setTimeout

http://www.w3schools.com/jsref/met_win_settimeout.asp

而你的問題:如果你把var t =setTimeout(function() {之前預期它會工作

希望這些幫助,思南。

+0

爲什麼它應該在我將setTimeout設置爲名爲「t」的變量時工作? – Karem 2010-03-07 15:40:04