你這樣做太複雜了,並不是說它實際上不適合JS。
請考慮這一點。
// define new custom event
$(document).on('isWorking.my', function(e, flag) {
if (flag)
$('.statusIndicator').stop().fadeIn('fast').addClass('working')
else
$('.statusIndicator').stop().fadeOut('fast').removeClass('working')
})
// now in every place you want to update if you are working or not
// instead of
$('#indicator').text(1)
// you are doing this to start working
$(document).trigger('isWorking.my', [1])
// or this to stop
$(document).trigger('isWorking.my', [0])
注意jQuery的事件,您可以通過額外參數到事件處理程序,語法如下:
// triggering event and passing params
$(obj).trigger('someEvent', [param1, param2, param3...])
// handling event
$(obj).on('someEvent', function(e, param1, param2, param3) {
....
})
您可以改進具有等多個標誌這一想法,但如果你真的有麻煩等着對於異步操作完成,如Ajax請求,你的真正的方法是使用承諾:
// two ajax operations
function loadCategories() {
return $.getJSON('/category')
}
function loadProducts() {
return $.getJSON('/product')
}
// something that should happen when both of them finished
function renderMyUI(categories, products)
// and kick off
$.when(loadCategories(), loadProducts()).done(renderMyUI)
// or a click event should kick it off
$('button.load').on('click', function() {
$.when(loadCategories(), loadProducts()).done(renderMyUI)
})
它的工作原理?我很驚訝,因爲你只能得到'div'的'text()'一次。所以它不會再檢查它。你爲什麼要定義'doOnlyOnce'兩次? – putvande
因爲我測試了腳本中的警報,並且一直保持警戒狀態,所以我認爲這就是使用fadeIn行的方式,一遍又一遍地運行它,所以這是我的嘗試,只做腳本一次執行該代碼而不是一遍又一遍。我其實應該刪除那一點,我認爲這可能導致瀏覽器崩潰。 –
哦,我看到你在說什麼,是的,我只定義了一次progressChecker ..嗯,偉大的一點,所以我需要定義循環內,讓它不斷地檢查一遍又一遍? –