我正在尝试在我的网页中同时拥有一千个分隔符和仅限数字的文本框。我尝试过很多东西,从网络上看都没有成功。 这是我的代码:
$(".price").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
$(".price").keyup(function (e) {
num = $(this).val().replace(',', '');
// separate the whole number and the fraction if possible
var sep = ",";
var decpoint = ".";
a = num.split(decpoint);
x = a[0]; // decimal
y = a[1]; // fraction
z = "";
if (typeof (x) != "undefined") {
// reverse the digits. regexp works from left to right.
for (i = x.length - 1; i >= 0; i--)
z += x.charAt(i);
// add seperators. but undo the trailing one, if there
z = z.replace(/(\d{3})/g, "$1" + sep);
if (z.slice(-sep.length) == sep)
z = z.slice(0, -sep.length);
x = "";
// reverse again to get back the number
for (i = z.length - 1; i >= 0; i--)
x += z.charAt(i);
// add the fraction back in, if it was there
if (typeof (y) != "undefined" && y.length > 0)
x += decpoint + y;
}
$(this).val(x);
});
在这段代码中,我混合了两种解决方案。一个用于分隔符,另一个用于仅数字。有人可以帮我解决这个问题吗?