使用javascript处理文本区域输入键 [英] Handling Enter Key on Text Area using javascript

查看:107
本文介绍了使用javascript处理文本区域输入键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上有5个文本区域,我想要在第一个文本区域上按下回车键并在其他文本区域的输入键上输入不同的事件。你可以建议一下如何实现这一点。

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.

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

在第一个文本区域输入 alert('Text Area 1点击');

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

当在另外4个文本区域, alert('Other Text Area'click ');

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

可以使用jquery来实现。

Can this be acheived using jquery.

推荐答案

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");
     }
   }
});

在某些版本的FFX中按< Tab> ,e。没有设置(保持0),但e.keyCode是(9)。

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

你也可以将其缩短到

$("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");
      }
    }
});

另一件事情是我喜欢在这里添加类,而不是找到第一个textarea是cos这更多通用解决方案,可以满足任何文本区域。

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.

这篇关于使用javascript处理文本区域输入键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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