Javascript 在按Enter键时将textarea数据附加到评论文章
我正在创建一个评论系统,其结构如下:Javascript 在按Enter键时将textarea数据附加到评论文章,javascript,php,jquery,Javascript,Php,Jquery,我正在创建一个评论系统,其结构如下: <div id="main_comment_DIV_id_no"> //Some user comment </div> <div "reply_DIV"> <textarea name="reply_comment" id="reply_comment" rows="1" style="width:100%"> </textarea> </div> //一
<div id="main_comment_DIV_id_no">
//Some user comment
</div>
<div "reply_DIV">
<textarea name="reply_comment" id="reply_comment" rows="1" style="width:100%">
</textarea>
</div>
//一些用户评论
我想在按下Enter
键时将textarea数据附加到主注释(同时更新数据库)部分
如果只有一个(或几个)DIV
s,我可以很容易地实现这一点,但这里我有n个DIV
s,因此我正在寻找一种解决方案,只将第n个回复数据附加到第n个主注释DIV
中
任何帮助都非常有用?以下是逻辑。那可能对你有帮助。
当您单击enter键时,调用ajax函数并传递回复注释。在php端,将该注释添加到数据库中,并从数据库中获取所有消息。关于ajax的成功
$('#main_messages_container').html(null);
$('#main_messages_container').html(res);
这将为您提供所有更新的新消息。在这种情况下,不需要附加任何div容器
详细答复:
$('#enter_key_button').on('click',function(){
$.ajax({
type: 'post',
url: 'process.php',
data: {textarea : textarea},
success: function (res) {
//alert(res);
$('#main_messages_container').html(null);
$('#main_messages_container').html(res);
}
});
});
您可以尝试使用keyup事件和jquery类选择器。您不应该使用id作为选择器,因为您说过您有n个主注释dive,所以n个div的id不应该相同
<body>
<script type="text/javascript">
$(document).ready(function(){
$('[name="reply_comment"]').keyup(function(e){
if(e.which === 13){
var comment = $(e.currentTarget).val(),
commentDiv = $('.main_comment_DIV_id_no');
//you have the comment here, so you can call an ajax request to update it in the database.
$(e.currentTarget).val("");
//if the blank div where you want to add the comment is already present, then write
$(commentDiv[commentDiv.length-1]).text(comment);
// Else no need to add the blank div initially, just create a new div and add the comment there.
$(commentDiv[commentDiv.length-1]).after('<div class="main_comment_DIV_id_no">'+comment+'</div>');
}
})
})
</script>
<div class="main_comment_DIV_id_no">
Some user comment
</div>
<div class="main_comment_DIV_id_no">
Some user comment2
</div>
<div class="main_comment_DIV_id_no">
</div>
<div id="reply_DIV">
<textarea name="reply_comment" id="reply_comment" rows="1" style="width:100%" ></textarea>
</div>
</body>
$(文档).ready(函数(){
$('[name=“reply_comment”]')。键控(函数(e){
如果(e.which==13){
var comment=$(e.currentTarget).val(),
commentDiv=$('.main_comment_DIV_id_no');
//这里有注释,因此可以调用ajax请求在数据库中更新它。
$(e.currentTarget).val(“”);
//如果要添加注释的空白div已经存在,则写入
$(commentDiv[commentDiv.length-1])。文本(注释);
否则,不需要首先添加空白div,只需创建一个新div并在其中添加注释即可。
$(commentDiv[commentDiv.length-1])。在(“”+注释+“”)之后;
}
})
})
一些用户评论
一些用户评论2
您在这里尝试了什么?添加您的代码。。。我们可以试着调试它。但是创建它完全是你的任务。@Ronak和j809谢谢你的评论,我只想知道我应该在这里应用的逻辑……我试着运行我的大脑,但没有运气当你按enter键时哪个元素有焦点?@user3803005:那么,你想用ajax吗?当你们点击输入时,所有旧的和新的信息都应该出现在主容器中。正当