2012-03-15 26 views
2

如何在顯示錯誤信息後2秒後顯示none none錯誤信息?在JQuery中2s後顯示none全部錯誤信息

喜歡的東西

$(document).ready(function() { 
    $('#error_message').show().delay(2000).fadeOut('slow'); 
}); 

所以,每當顯示一個錯誤信息,錯誤信息要持續2秒後,要顯示出來。 很難在每個節點內改變它。所以我想通常編寫代碼,這將在每個頁面中都有效。 因此,在顯示錯誤消息的地方,它希望在2秒內顯示出來。

可能嗎?

+0

不知道你需要的節目()位。也許兩個命令 - 一個顯示,一個設置延遲?目前會發生什麼 - 上述代碼出現任何錯誤? – 2012-03-15 13:09:45

+0

@Matt Gibson:其實這個代碼'$('#error_message')。show()。delay(2000).fadeOut('slow'); '適合我。它會首先讓'display:block'延遲2秒,然後'display:none'慢慢地...... – 2012-03-15 13:15:39

回答

1

如果您在document.ready上執行此操作,它將執行一次,而不是每次顯示錯誤消息。

用函數實現延遲fadeOut以顯示錯誤。

function display_error(message) { 
    $('#error_message').html(message); 
    $('#error_message').show().delay(2000).fadeOut('slow'); 
} 

如果這不工作或不適合,你也可以將其綁定到一個事件並觸發顯示該事件。

樣品
http://jsfiddle.net/28XTM/

+0

這裏我需要在錯誤出現的地方調用這個函數。無論如何,有'#error_message'顯示的地方,它希望在2秒內顯示出來,而不必在每個地方調用該函數。 – 2012-03-15 13:19:57

0

要隱藏錯誤使用「#error_message」爲ID,但如果你有一個以上的元素,那麼你應該使用「.error_message」爲一類,而不是ID。

$(document).ready(function() { 
    $('#error_message').delay(2000).fadeOut('slow'); // For id and use $('.error_message') for class 
    //Or 
    setTimeout(function(){ 
     $('#error_message').fadeOut('slow'); // For id and use $('.error_message') for class 
    }, 2000) 
});​ 

小提琴是here

不要使用ID $(「#someId」)超過一個元素,它應該是唯一的,而不是使用類$(「SomeClass的」),當你有這樣的事情

<div class="someClass">This is an error.</div> 
<div class="someClass">This is an error.</div> 
0

使用ajaxError事件處理程序用於顯示項目中所有ajax調用的錯誤。就在這個代碼粘貼到你的頁面佈局:

$(function(){ 
    $(".error_message").ajaxError(function (event, xhr, status, error) { 
      $(this).html(error).show().delay(2000).fadeOut('slow'); 
    }); 
}); 
0

使用的setTimeout:

<div id="error_message"> 
    Put your error message here 
</div> 

<button id="btn_error">Show error</button> 

<script> 

// Init sample 
$('#error_message').hide(); 

function display_error(message) { 
    $('#error_message').html(message); 
    $('#error_message').show(); 
    setTimeout(function() { 
     $('#error_message').hide(); 
    }, 2000); 
} 

$("#btn_error").click(function() { 
    display_error("Show this test message"); 
}); 
</script>