2010-11-23 112 views
5

我用下面添加一個號碼:JS jQuery的,總是有一些顯示至少有兩位00

<div id="count">00</div> 
<div id="count">03</div> 
<div id="count">08</div> 
<div id="count">12</div> 

$('#count').text(function(i,txt) { return parseInt(txt, 10) + 1; }); 

我一直想有,兩個人2個地方,即使00的數量爲在10以下。我怎麼能得到上面的JS,總是返回200個地方?所以如果這個數字計算爲3,它會將#03注入到#count中?

由於

+1

僅供參考,具有相同ID的多個元素是無效的。這將無法正確有效,JavaScript可能會在不同的瀏覽器上出現意外情況。 – Hamish 2010-11-23 19:56:45

回答

5
$('#count').text(function(i,txt) { var c = parseInt(txt, 10) + 1; return (c<10) ? "0"+c : c; }); 

編輯:但是具有相同的ID的多個元件是要去引起問題的某個地方。

+0

非常好,謝謝 – AnApprentice 2010-11-23 19:45:16

2

您可以添加"0"如果是小於10,是這樣的:

$('#count').text(function(i,txt) { 
    var num = parseInt(txt, 10) + 1; 
    return num < 10 ? "0" + num : num; 
}); 

認爲這只是一個例子,但是如果它沒有注意到的ID必須是唯一的。

0

試試這個:

$('#count').text(function(i,txt) { return txt.length == 1 ? '0'+txt : txt; }); 
5

下面是從別人有點不同的方法。不使用條件運算符。

$('#count').text(function(i, txt) { 
    return ("0" + (+txt + 1)).slice(-2); 
}); 

這只是假設,它需要額外的0,然後返回字符串中的最後兩個字符的份額。

+0

我喜歡這個。比有條件的解決方案短得多。 – 2012-05-17 19:18:22

相關問題