2015-05-20 56 views
0

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

基本上输入与在html缺省值开始[这是只读值]:

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

然后,一个jQuery“按键KEYDOWN”函数检查按下的键的索引相对于只读单词,如果索引位于单词之前或之后,则返回“true”,这将添加字符,否则将返回false,这将防止添加字符。问题是,如果我在单词前键入,它将只读单词的索引增加两次,它应该增加1(因为只读单词已经为每个字符移动了一个索引)。 这是'keypress keydown'功能;希望这很容易理解(让我知道如果不是这样,我想在这更好的为好):

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插件插入符号。

请让我知道如果您有任何意见或建议,或者如果解决我的问题是类似的解决另一个问题就在这里

+0

许多if语句是有它的if语句 –

回答

3

你应该只使用一个事件。在下面的语句中keypress或​​:

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

这将在一个单一的按键火灾事件的两倍。

所以,你的声明更改为:

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

是的!谢谢:) 顺便说一句,“按键”只是不起作用,但当我把它改为'keydown'时,它才能完美地完成! –