简体   繁体   English

如何在JavaScript中的按键事件上获取文本框的值

[英]How to get the value of a textbox on keypress event in javascript

I am making a chrome extension in which I want to do some string replacement in the text when the enter key is pressed in a focussed textarea. 我正在做一个chrome扩展程序,在其中我想在聚焦的textarea中按Enter键时在文本中进行一些字符串替换。 Here is the code snippet: 这是代码片段:

var elems = document.getElementById("ChatTabsPagelet").getElementsByTagName("textarea"),i;
matchClass = "uiTextareaAutogrow";

for (i in elems) {
    if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')> -1) {
    text = elems[i].value;          
            elems[i].onkeyup = function(evt) {
              if(evt.keyCode == 13){
               alert(elems[i].value);
              }
      };
   }
}

Basically I am looking for all the textareas with the class uiTextareaAutogrow and I just want to access their values when the enter key is pressed in any of those textareas. 基本上,我正在使用uiTextareaAutogrow类查找所有文本区域,而我只想在这些文本区域中的任何一个按下Enter键时访问它们的值。 However, I always get undefined in the alert box when I try the extension out on a webpage. 但是,当我在网页上尝试扩展时,总是在警报框中未定义 I guess the keyup event is fired but it is not able to get a handle to the particular textarea. 我猜keyup事件被触发了,但是它无法获取特定textarea的句柄。 Where am I going wrong? 我要去哪里错了?

Note: I am keen on using javascript only(not jquery) as I want the extension to be really light. 注意:我很想只使用javascript(而不是jquery),因为我希望扩展名很轻。

The following example should do the trick! 以下示例可以解决问题! ( see a working JSFiddle here ). 请参见此处的正常工作的JSFiddle )。

You shouldn't use for..in with array-like objects as the order cannot be guaranteed. 您不应该将for..in用于类似数组的对象,因为不能保证顺序。 Also when the value of an element is referenced in a dynamic function you need to use this.value . 同样,在动态函数中引用元素的值时,也需要使用this.value

var elems = document.getElementsByTagName("textarea")
matchClass = "uiTextareaAutogrow";
for(var i = 0, n = elems.length; i < n; i++) { // <---- simple for loop
    if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')> -1) {
             elems[i].onkeyup = function(evt) {
                  if(evt.keyCode == 13){
                      alert(this.value);
                   }
            }  
    }
}

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

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