我正在尝试编写一个将输入的当前值(int)转换为单词的脚本。
var th = ['', 'thousand', 'million', 'billion', 'trillion'];
var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'You must enter a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
}
else if (n[i] != 0) {
str += tw[n[i] - 2] + ' ';
sk = 1;
}
}
else if (n[i] != 0) {
str += dg[n[i]] + ' ';
if ((x - i) % 3 == 0) str += 'hundred ';
sk = 1;
}
if ((x - i) % 3 == 1) {
if (sk) str += th[(x - i - 1) / 3] + ' ';
sk = 0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
}
return str.replace(/\s+/g, ' ');
return false;
}
var input = $('#numbers'),
label = $('.words'),
converted = toWords(input.val());
input.bind('keyup keydown', function() {
converted = toWords(this.value)
setTimeout(function() {
label.empty().text(converted);
}, 1000);
});
此时,我可以输入任何我输入的内容,但是一旦我通过 toWords 函数发送它,它就会获取页面加载时给出的输入值。
换句话说,它不会用我输入的新数字更新输入字段的值,然后它应该转换为单词。
有任何想法吗?- http://jsfiddle.net/qTBxv/211/