2011-09-30 114 views
0

我有以下代碼:遞增變量

的javascript:

var counter = 0; 
var totalItems = 8; 
var restItems = $num-totalItems; 
if (restItems==22) { 
    $('#next').click(function(e) { 
     e.preventDefault(); 
     counter++; 
     updatestatus();  
    }); 
}  

function updatestatus() { 
    totalItems = totalItems + 8 * counter; 
} 

HTML:

<input type = "button" id="next" value="click me"> 

我要的是,在我點擊該按鈕,totoalItems等於8,每次當我點擊它時,最多加上8個項目,但是在那個代碼不起作用的時候,給我一個非常大的數字,任何人都可以幫我弄清楚,非常感謝。

+0

什麼是'$ num'? –

+0

抱歉,$ num = 30; – smith

+1

如果你只是每次加8就不需要8乘以? – Alex

回答

0
var counter = 0; 
var totalItems = 8; 
var restItems = $num - totalItems; 

if (restItems == 22) { 
    $('#next').click(function(e) { 
     e.preventDefault(); 
     counter++; 
     updatestatus(); 
    }); 
} 

function updatestatus() { 
    totalItems = totalItems + 8 * counter; 
} 

有了這個代碼,每次運行時updatestatus(),它通過其自身的價值8 * counter遞增totalItems。你並不需要增加它:

function updatestatus() { 
    totalItems = 8 + 8 * counter; 
} 

但理想情況下,我只希望簡化代碼:

var counter = 0; 
var totalItems = 8; 
var restItems = $num - totalItems; 

$('#next').click(function(e) { 
    if (restItems == 22) { 
     e.preventDefault(); 
     totalItems += 8; 
    } 
}); 
2

你爲什麼乘上櫃臺?

totalItems = totalItems + 8; 
+0

要麼這樣,要麼'totalItems = 8 * counter' – Nick