2013-08-21 34 views
0

我有一組問題,並希望在它們上方顯示一個簡單的進度計數器。 下面的代碼工作正常,但我想知道是否有人可以建議重構,因爲它們是實現這一目標的更好方法。簡單計數使用jQuery

var totalCount = $('#questions li').length, 
     count = 1; 
    $('.progress').html("Question " + count + " of " + totalCount);     

    // Increment by 1 on each click 
    $('.btn-next').click(function(){       
     count ++ ; 

     // remove current count 
     $('.progress').empty(); 

     // drop in new count 
     $('.progress').html("Question " + count + " of " + totalCount); 
    }); 

    // Decrease by 1 on each click 
    $('.btn-prev').click(function(){ 
     count -- ; 

     // remove current count 
     $('.progress').empty(); 

     // drop in new count 
     $('.progress').html("Question " + count + " of " + totalCount); 
    }); 

回答

2

你可以幹這個代碼了很多。試試這個:

var totalCount = $('#questions li').length + 1, // add 1 as .length is 0 based 
    count = 1; 

$('.btn-next, .btn-prev').click(function(){       
    count = $(this).hasClass('btn-next') ? count - 1 : count + 1; 
    $('.progress').html("Question " + count + " of " + totalCount) 
}); 

需要注意的是,你要替換的html()反正你不需要empty()

+0

喜羅裏 當我運行腳本,這是輸出

Question NaN of 17
任何想法楠? –

+0

'NaN'表示結果不是數字 - 通常來自嘗試對字符串和整數執行數學運算。你可以把你的代碼放到http://jsfiddle.net中,這樣我就可以看到發生了什麼? –

+0

http://jsfiddle.net/bobby_bob/k4Ptg/4/ –