我使用这行代码动态地将一个CSS类添加到包含flash消息的div:
$("div#flash_notice").toggleClass('success');
javascript文件位于我的micropost
视图中,以便在我添加帖子时执行。一切都很顺利,除非我在没有刷新页面的情况下添加两个帖子,因为当它切换回去删除该类时,flash消息会丢失它的样式。我怎么能绕过这个?
答案 0 :(得分:1)
不要使用切换类。使用addClass,只有在没有类时才会添加类:
$("div#flash_notice").addClass('success');
答案 1 :(得分:0)
您只能将该类添加到尚未具有该类的元素:
$("div#flash_notice").not('.success').addClass('success');
答案 2 :(得分:0)
您可以像其他人提到的那样使用.addClass
方法。在回答您关于动画的评论时,您可以执行以下操作:
var flashNoticeTimeout;
var fadeOutDelay = 1000;
function onPostAdded() {
var $flashNotice = $("#flash_notice"); // Get flash_notice element
$flashNotice.show().addClass("success"); // Show the flash element and then add the 'success' class.
// Need to use .show because the .fadeOut later on will have hidden this element
clearTimeout(flashNoticeTimeout); // Clear any previous timeouts. If the user button adds a post, then adds another post before the element has faded out, this will clear the last timeout so the element isn't hidden before 'fadeOutDelay`
flashNoticeTimeout = setTimeout(function() { // Trigger this anon function after 'fadeOutDelay' milliseconds (1000 milliseconds = 1 second)
$flashNotice.fadeOut(); // Fade out the element
}, fadeOutDelay);
}
请参阅fiddle了解演示。
答案 3 :(得分:0)
或更简单:http://jsfiddle.net/LekisS/L2kvP/1/
。$( 'DIV#flash_notice')延迟(1000).fadeOut();