检测退格和del“输入”。事件? [英] Detect backspace and del on "input" event?

查看:134
本文介绍了检测退格和del“输入”。事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

怎么做?

我试过:

var key = event.which || event.keyCode || event.charCode;

if(key == 8) alert('backspace');

但它不起作用......

but it doesn't work...

如果我在按键事件上执行相同操作,但我不想使用按键,因为它会在输入字段中输出键入的字符。我需要能够控制

If I do the same on the keypress event it works, but I don't want to use keypress because it outputs the typed character in my input field. I need to be able to control that

我的代码:

  $('#content').bind('input', function(event){

    var text = $(this).val(),
        key = event.which || event.keyCode || event.charCode;

    if(key == 8){
      // here I want to ignore backspace and del
    }

    // here I'm doing my stuff
    var new_text = 'bla bla'+text;
    $(this).val(new_text);
  });

除了我添加的val()$ b之外,我的输入中不应附加任何字符$ b实际上应该完全忽略用户的输入,只有按键动作对我很重要

no character should be appended in my input, besides what I'm adding with val() actually the input from the user should be completely ignored, only the key pressing action is important to me

推荐答案

使用 .onkeydown 并取消删除 return false; 。像这样:

Use .onkeydown and cancel the removing with return false;. Like this:

var input = document.getElementById('myInput');

input.onkeydown = function() {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 )
        return false;
};






或者使用jQuery,因为你添加了一个jQuery标签问题所在:


Or with jQuery, because you added a jQuery tag to your question:

jQuery(function($) {
  var input = $('#myInput');
  input.on('keydown', function() {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 )
        return false;
  });
});

这篇关于检测退格和del“输入”。事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆