2016-09-06 58 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