我有多个具有相同类但不同 id 和 data-ref 的文本区域供我自己引用。 我正在使用以下 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)
代替类名来获取当前的textarea值。更改您的代码如下:
$(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
}
}
});
});
关于javascript - jQuery 仅获取第一个文本区域的值,而不获取其他文本区域的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48604780/