2010-09-21 76 views
0

有時可能會調用該函數太快,並創建多個元素,但由於它使用的ID對每個實例都不是唯一的,因此淡出和移除div的部分僅適用於頂級元素,而不是全部。所以我最終得到了一個靜態div標籤,它不是淡入淡出。重複JS函數的最佳方法

我能想到的最好的事情就是簡單地重複這個過程。我該怎麼做,還是有更好的方法?

document.triggerNotification = function (type, message) { 
    jQuery(document.body).append("<div class='push-notification push-"+type+"' id='notification'>"+message+"</div>"); 

    jQuery('#notification').delay(1500).fadeOut(1200, function() { 
     jQuery('#notification').remove(); 
    }); 
} 

回答

3

只是緩存創建的元素,不需要IDS

function (type, message) { 
    var el = $("<div class='push-notification push-"+type+"'>"+message+"</div>"); 
    jQuery(document.body).append(el); 

    el.delay(1500).fadeOut(1200, function() { 
     el.remove(); 
    }); 
} 
+0

這是最好的解決方案。我還會注意到,在這種情況下,setTimeout比延遲更合適。延遲更適合排隊的fx,但由於您只會在元素上執行一個動畫,setTimeout就足夠了。 – Ender 2010-09-21 20:05:21

0

給他們提供唯一的ID如何?

var notificationCount=0; 
document.triggerNotification = function (type, message) { 
    notificationCount++; 
    var notificationId="notification"+notificationCount; 
    jQuery(document.body).append("<div class='push-notification push-"+type+"' id='"+notificationId+"'>"+message+"</div>"); 

    jQuery('#'+notificationId).delay(1500).fadeOut(1200, function() { 
     jQuery('#'+notificationId).remove(); 
    }); 
} 
+0

+1擊敗我。 :) – casablanca 2010-09-21 19:56:49

+0

根本不需要身份證件(請參閱我的回答) – mikerobi 2010-09-21 19:59:49

+0

有時候你會逐字地閱讀這個問題。你的方法獲勝! – spender 2010-09-21 20:03:32

0

幾個選項:

  1. 讓你的ID的獨特通過附加的越來越多(例如)。
  2. 使用新類作爲您感興趣的行的指示符,然後使用「.notificationID」樣式選擇器附加fadeOut。
0

而不是使用的手柄動畫/刪除通知的ID,你可以簡單地創建它作爲自己的函數中的變量呼叫,從而給你一個方法來刪除它。事情是這樣的:

document.triggerNotification = function(type, message) { 
    var notification = $("<div class='push-notification push-" + type + "'>" + message + "</div>"); 
    jQuery(document.body).append(notification); 

    setTimeout(function() { 
     notification.fadeOut(1200, function() { 
      notification.remove(); 
     }) 
    }, 1500); 
}; 

另外,我覺得在這種情況下setTimeout.delay()更合適。雖然它們都可以工作,但.delay()旨在用於排列多個動畫。在這種情況下,setTimeout就足夠了,因爲你只調用一個動畫。在這裏看到的文檔:http://api.jquery.com/delay/

最後,這裏是代碼的工作演示,我提供:http://jsfiddle.net/WqwsN/

您可以通過點擊該按鈕,只要你喜歡,你可以得到儘可能多的通知看,他們會按照它們添加的順序淡出。