在你說它的重複之前,我不問如何真正格式化價格。但是詢問我做錯了什麼,或者我應該做些什麼來按照我想要的方式來實現它。輸入價格格式化javascript,其中錯誤
我做了價格的格式(實際上通過複製從某處的代碼) http://jsfiddle.net/qwY24/
像價格1
,但現在我想格式化的價格在輸入字段本身(價格2),它工作得很好,直到6位數,但之後就會搞砸了。它有兩個問題
- 格式後6位數搞砸
- 時按返回鍵(刪除號碼)價格不格式化後6位數只有
代碼
$(".price1").on("keyup",function(){
var price = $(this).val();
$(".formatted1").text(price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
});
$(".price2").on("keyup",function(){
var price = $(this).val();
price = price.replace(",","");
$(".price2").val(price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
$(".formatted2").text(price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
});
<label>Price 1</label> <input type="text" class="price1" /><br /> <label><b>Price 1 Formatted:</b></label> <span class="formatted1"></span><br /><br /><br /> <label>Price 2</label> <input type="text" class="price2" /><br /> <label><b>Price 2 Formatted</b></label> <span class="formatted2" ></span><br /><br /><br />
'\ d \ d \ D'可以替換爲\ d {3}'。並嘗試使用'*''+''?'。他們比較0或更多,1或更多,0或1. – 2013-03-22 09:08:10
@allendar謝謝你,但我還沒有真正理解正則表達式。我應該花一些時間學習*代碼是從某處複製的:) – cjmling 2013-03-22 09:47:23