首页 > 解决方案 > Jquery在按Enter键时获取textarea值

问题描述

我试图在按下回车键时获取文本区域的值,但获取值未定义。

jQuery(".comment-form .comments-text").on('keypress', function (e) {
    if(e.which === 13 && !e.shiftKey) {
        e.preventDefault();
        
        var text = jQuery(this).value;
        console.log(e);
    }
});

on keypress 工作正常,但无法获取我输入的文本。

标签: javascriptjquery

解决方案


此代码应该可以工作:

HTML

<form class="comment-form">
  <textarea class="comments-text"></textarea>
</form>

jQuery

$(".comment-form .comments-text").on('keypress', function(e) {
  if (e.which === 13 && !e.shiftKey) {
    e.preventDefault();

    var text = e.target.value;
    console.log('text', text);
  }
});

推荐阅读