简体   繁体   English

在JavaScript中,如何处理退格键并删除按键以执行其按键功能以及其他操作?

[英]In JavaScript, how do I handle backspace and delete key presses to perform its key function as well as extra stuff?

I have a text box where I would like to be able to press the backspace or delete key in it, and have these key presses perform their relevant function, ie, have the character next to the cursor removed, but in addition I would like extra stuff to be done on those keep press events as well. 我有一个文本框,我希望可以在其中按下退格键或删除键,并让这些按键执行它们的相关功能,例如,删除光标旁边的字符,但是除此之外,我还想那些要做的事情也会保持新闻发布。

My solution so far involved calling a function that checks for the backspace or delete keyCode on the onKeyDown event, but the problem is once it handles the extra stuff I want done associated with those key presses, it does not actually perform the key functionality of removing the characters in the text box. 到目前为止,我的解决方案涉及在onKeyDown事件上调用一个用于检查退格或删除keyCode的函数,但是问题是,一旦它处理了我想要完成的与那些按键相关的额外工作,它实际上就不会执行删除键的功能文本框中的字符。 A code example is shown below. 一个代码示例如下所示。 This gives the effect that the keys don't work to the user when they are making edits in the text box. 这样可以使按键在文本框中进行编辑时对用户不起作用。

function foo(obj)
{
      // if key is backspace or delete ...
      if ((event.keyCode == 8 || event.keyCode == 46))
      {
           // do extra stuff here.        
      }
}

I was wondering if there is a way of triggering the backspace or delete key functionality without having to determining the cursor position and manipulating the strings in the text box (and not involving jQuery in solution)? 我想知道是否有一种触发退格键或删除键功能的方法,而不必确定光标位置和操纵文本框中的字符串(并且在解决方案中不涉及jQuery)?

It seems that I was calling an existing function, written by someone else, and in that function it had the following code in it: 看来我正在调用别人编写的现有函数,并且在该函数中包含以下代码:

event.returnValue = false;

Apparently, this property seems to prohibit the default action connected to the event. 显然,此属性似乎禁止连接到该事件的默认操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM