我有几种方法看起来很相似,并且似乎是重构的理想选择:
// if there is already a decimal in the value and user presses period on keyboard (190) or decimal on keypad (110) then prevent entry of that period or decimal
function oneDecimalPointOnly(e) {
var v = $(this).val();
if (v.indexOf('.') > -1 && $.inArray(e.keyCode, [190, 110]) > -1) {
e.preventDefault();
}
}
// if there is already a negative sign in the value and user presses minus on keyboard (189) or subtract on keypad (109) then prevent entry of that minus or subtract
function oneNegativeSignOnly(e) {
var v = $(this).val();
if (v.indexOf('-') > -1 && $.inArray(e.keyCode, [189, 109]) > -1) {
e.preventDefault();
}
}
它们的绑定如下:
$(':text').on('keydown', oneDecimalPointOnly);
$(':text').on('keydown', oneNegativeSignOnly);
按照书面规定,它们可以正确完成任务,从而防止在文本框中输入多个小数或负数。
对于重构,这是我尝试过的:
function oneDecimalPointOnly(e) {
limitCharacterToOne(e, '.', [190, 110]);
}
function oneNegativeSignOnly(e) {
limitCharacterToOne(e, '-', [189, 109]);
}
// if character is already in the value and user presses a key in the keyCodes array then prevent entry of that character
function limitCharacterToOne(e, character, keyCodes) {
var v = $(this).val();
if (v.indexOf(character) > -1 && $.inArray(e.keyCode, keyCodes) > -1) {
e.preventDefault();
}
}
重构版本不会阻止在文本框中输入多个小数或负数。
重构版本需要进行哪些修改,以防止输入多个小数或负数?
答案 0 :(得分:1)
function oneDecimalPointOnly(e) {
limitCharacterToOne(e, '.', [190, 110]) ;
}
function oneNegativeSignOnly(e) {
limitCharacterToOne(e, '-', [189, 109]);
}
function limitCharacterToOne(e, character, keyCodes) {
var v = $(e.target).val();
if (v.indexOf(character) > -1 && $.inArray(e.keyCode, keyCodes) > -1) {
e.preventDefault();
}
}