2016-09-06 55 views
3

当从输入键控事件中移除预定字符时触发两次。我怎样才能防止这一点?从输入中删除字符时,如何防止keyup事件触发两次?

HTML

<input type="text" id="search"> 

JS

var block = { 
    'ch1': { 
     'key':'/', 
     'keycode':'191' 
    }, 
    'ch2': { 
     'key':':', 
     'keycode':'186' 
    }, 
    'ch3': { 
     'key':'=', 
     'keycode':'187' 
    } 
} 

$('#search').on('keyup',function(){ 
    console.log(checkChar($(this))); 
}); 

function checkChar($this){ 

    var txt = $this.val(), 
     flag = true; 

    for(var i=0; i<txt.length; i++) { 

    $.each(block,function(k,v){ 

     if (txt[i] === v.key) { 
     $this.val(txt.slice(0,-1)); 
     flag = false; 
     return false; 
     } 

    }); 

    } 

    return flag; 

} 

JSBIN

https://jsbin.com/mirocepiqo/1/edit?html,js,output

+2

的问题是,当您松开Shift键,生成keyup事件也是如此。尝试过滤你感兴趣的钥匙。 –

回答

2

event运行,检查event.shiftKey,如果条件是truereturn

$('#search').on('keyup',function(e){ 
    var res = checkChar(e, $(this)); 
    if (res !== undefined) { 
    console.log(res); 
    }; 

}); 

function checkChar(e, $this){ 
    if (e.shiftKey) { 
    return 
    }; 
    var txt = $this.val(), 
     flag = true; 

    for(var i=0; i<txt.length; i++) { 

    $.each(block,function(k,v){ 

     if (txt[i] === v.key) { 
     $this.val(txt.slice(0,-1)); 
     flag = false; 
     return false; 
     } 

    }); 

    } 

    return flag; 


} 
+0

这正是我想要的。谢谢 – midstack