jQuery if语句被触发两次

时间:2015-05-20 14:10:37

标签: javascript jquery html input readonly

我试图使用jQuery在html输入中编写只读值,并且我遇到了一个问题,其中单个if语句触发两次。

基本上输入以html中的默认值开始[这是只读值]:

<input id="main-field" type="text" value="dan" >

然后,jQuery&#39; keypress keydown&#39;函数检查按下的键相对于只读单词的索引,如果索引在单词之前或之后返回&#39; true&#39;这将添加字符,否则将返回false,这将阻止添加字符。问题是如果我在单词之前输入它会增加readonly单词的索引两次,其中它应该增加1(因为readonly单词已经为每个char移动了一个索引)。 这是&#39; keypress keydown&#39;功能;希望它很容易理解(如果没有,请告诉我,我也希望在这方面做得更好):

var readOnlyEnd = $('#main-field').val().length,
    readOnlyStart = 1;

$('#main-field').on('keypress keydown', function(event) {

    var character = String.fromCharCode(event.keyCode).toLowerCase();

    // note: using the jquery caret plugin
    var pos = $('#main-field').caret();

    // handling new character between 'a' and 'z' and the delete char.
    if (((character >= 'a') && (character <= 'z')) || (event.which == 8)) {

        // if delete is pressed:
        if (event.which == 8) {
            if (pos == readOnlyEnd) return false;
            else if (pos < readOnlyStart) {
                if (pos == 0) return true;
                if (pos > 0) {
                    console.log('reudce index!!');
                    // Will reduce indexes.
                    readOnlyStart -= 1;
                    readOnlyEnd -= 1;
                    return true; // Will delete.
                }
            }
            else if ((pos >= readOnlyStart) && (pos < readOnlyEnd)) return false;
        }

        // within the word.
        else if ((pos >= readOnlyStart) && (pos < readOnlyEnd)) return false;

        // before the readonly word. - HERE IS THE PROBLEM, INCREASING TWICE.
        else if (pos < readOnlyStart) { 
            readOnlyStart += 1;
            readOnlyEnd += 1;
            return true; // Will add character
        }
        else {
            return true;
        }
    }
    else { 
        // In case something that doesn't affect the input was pressed (like left/right arrows).
        return true;
    }
});

注意:我在游标位置使用jQuery插入符插件。

如果您有任何想法或建议,或者我的问题的解决方案类似于此处另一个问题的解决方案,请告诉我

1 个答案:

答案 0 :(得分:3)

您应该只使用一个事件。以下陈述中的keypresskeydown

$('#main-field').on('keypress keydown', function(event) {

这将在一次按键时触发事件两次。

所以,将你的陈述改为:

$('#main-field').on('keypress', function(event) {
相关问题