[英]jQuery is picking up the value for first textarea only, not others
我有多個具有相同類的textarea,但ID和數據引用不同,僅供我參考。 我正在使用以下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
}
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.