【问题标题】:can these methods involving an event be refactored?这些涉及事件的方法可以重构吗?
【发布时间】:2019-11-11 00:23:29
【问题描述】:

我有几个方法看起来很相似,并且似乎是重构的好选择:

// 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();
    }   
}

但是,控制台显示此错误:

并且重构版本不会阻止在文本框中输入多个小数或负数。

重构版本需要进行哪些修改以防止输入多个小数或负数?

【问题讨论】:

标签: jquery


【解决方案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();
    }   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2016-11-20
    • 1970-01-01
    相关资源
    最近更新 更多