如何使用jquery按键在聚焦文本框中时插入符号?

时间:2015-11-30 11:48:13

标签: javascript jquery html

示例

<textarea name="test"></textarea>
$(document).keydown(function(e) { 
    if (e.keyCode == 27) { 
        var focused = document.activeElement; 
        $(focused).append("test string");  
        return false;    
    }
}); 

查找聚焦文本框/内容可编辑div并使用jquery追加字符串。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

我认为您不希望它触发任何其他元素?

使用if (document.activeElement.name == "test")执行此操作:

&#13;
&#13;
$(document).keydown(function(e) {
  if (e.keyCode == 27/*ESC*/) {
    if (document.activeElement.name == "test") {
      var focused = document.activeElement;
      $(focused).append("test string");
      return false;
    }
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="test"></textarea>
&#13;
&#13;
&#13;