Javascript 使用javascript处理文本区域上的输入键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7146659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:03:12  来源:igfitidea点击:

Handling Enter Key on Text Area using javascript

javascriptjqueryeventstextarea

提问by Abishek

I have 5 text areas on a page and I would like a specific event to occur on hitting the enter key on the first text area and a different event on enter key of the other text areas. Can you please suggest on how this can be acheived.

我在页面上有 5 个文本区域,我希望在按下第一个文本区域的 Enter 键时发生特定事件,并在其他文本区域的 Enter 键上发生不同的事件。您能否就如何实现这一点提出建议。

<TextArea></TextArea>
<TextArea></TextArea>
<TextArea></TextArea>
<TextArea></TextArea>
<TextArea></TextArea>

when hitting the enter on 1st Text Area, alert('Text Area 1 clicked');

当在第一个文本区域按下回车键时, alert('Text Area 1 clicked');

when hitting the enter on the other 4 Text Area, alert ('Other Text Area's clicked');

在其他 4 个文本区域上按回车键时, alert ('Other Text Area's clicked');

Can this be acheived using jquery.

这可以使用 jquery 来实现吗?

回答by Baz1nga

http://jsfiddle.net/26kN7/1/

http://jsfiddle.net/26kN7/1/

$("textarea").keyup(function(e) {
   var code = e.keyCode ? e.keyCode : e.which;
   if (code == 13) {  // Enter keycode
     if($(this).hasClass("first")) {
        alert("first ta clicked");
     } else {
         alert("the other ta clicked");
     }
   }
});

in some versions of FFX pressing <Tab>, e.which isn't set (remains 0), but e.keyCode is (9).

在某些版本的 FFX 中,按下<Tab>,e.which 未设置(仍为 0),但 e.keyCode 为 (9)。

you can also shorten this to

您也可以将其缩短为

$("textarea").keyup(function(e){
    if((e.keyCode || e.which) == 13) { //Enter keycode
      if($(this).hasClass("first")) {
        alert("first ta clicked");
      } else {
        alert("the other ta clicked");
      }
    }
});

the other thing note is I like adding the class here than finding the first textarea is cos this is more generic solution and could cater to any of the textareas.

另一件事要注意的是,我喜欢在这里添加类而不是找到第一个 textarea 是因为这是更通用的解决方案,可以迎合任何 textarea。

回答by David says reinstate Monica

You could try using:

您可以尝试使用:

$('textarea').keypress(
    function(e){
        if (e.keyCode == 13) {
            if ($(this).index() == 0) {
                // code for first textarea;
            }
            else {
                // code for others
            }
        }
    });

JS Fiddle demo.

JS小提琴演示

回答by Matt Ball

Check the whichproperty of the jQuery event objectto determine which key was pressed.

检查whichjQuery 事件对象属性以确定按下了哪个键。

$('textarea').first().keypress(function (e)
{
    if (e.which === 13) alert('Text Area 1 enter key pressed');
}).nextAll().keypress(function (e)
{
    if (e.which === 13) alert('Other Text Area enter key pressed');
});