jQuery只拾取第一个文本区域的值,而不是其他文本区域的值



我有多个具有相同类的文本区域,但不同的ids和数据引用供我自己参考。我正在使用以下jQuery脚本在按键(输入(上获取数据

$(document).ready(function(){
     $(document).on('keypress', '.comment-text',function(e){
        var key = e.which;
        if(key == 13)
        {
           e.preventDefault();
           var post_id = $(".comment-text").data('ref');
           var comment_text = $("#comment" + post_id).val();
       // or i can use the var comment_text = $(".comment-text").val();
       //both gives the same result
           console.log(comment_text);
           if(comment_text.replace(/(^s+|s+$)/g, '') === '')
           {
             $('.comment-text').val('');
             $('.comment-text').blur();
           }     
           else 
       {
        $("#no-comment").hide('fast');
        $('ul.post-id-'+ post_id).prepend('<li class="list-group-item"><a   href="/username/" class="text-dark"><b>username</b></a> '+ comment_text +' <span class="text-muted">Just Now</span></li>');
       $('.comment-text').val('');
       $('.comment-text').blur();
     return false; // Just a workaround for old browsers
           }

        }

      });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment-write">
   <ul class="list-group post-id04">

    <li id="#no-comment">No Comment Yet</li>
   </ul>
</div>
<textarea class="comment-text" data-ref="04" id="comment04" placeholder="Enter comment.."></textarea>

但它仅适用于第一个文本区域,不适用于多个/动态输入。

使用 $(this) 而不是类名来获取当前的文本区域值。 按如下方式更改代码:

$(document).ready(function(){
     $(document).on('keypress', '.comment-text',function(e){
        var key = e.which;
        if(key == 13)
        {
           e.preventDefault();
           var post_id = $(this).data('ref');
           var comment_text = $(this).val();
       // or i can use the var comment_text = $(".comment-text").val();
       //both gives the same result
            console.log(comment_text);
           if(comment_text.replace(/(^s+|s+$)/g, '') === '')
           {
             $(this).val('');
             $(this).blur();
           }     
           else 
       {
        $("#no-comment").hide('fast');
        $('ul.post-id-'+ post_id).prepend('<li class="list-group-item"><a   href="/username/" class="text-dark"><b>username</b></a> '+ comment_text +' <span class="text-muted">Just Now</span></li>');
       $(this).val('');
       $(this).blur();
     return false; // Just a workaround for old browsers
           }

        }

      });
});

最新更新