无法追加 jquery

Unable to append jquery

本文关键字:jquery 追加      更新时间:2023-09-26

>我无法附加页面,只是似乎刷新了我想在不刷新页面的情况下查看它的位置

索引.php

<div class="view_comment">
        <b>username :</b> <?php echo  $comment_comment;?>
</div> 
<div id="comment_type_area" class="comment_type_area">
        <form method="POST">
            <input type="text" class="comment" post_id="<?php echo $shared_id2; ?>" id="text_comment" placeholder="Write a Comment"></input>
            <input type="submit" id="post_button" ></input> 
        </form>
        </div>

Jquery.js

  $(document).ready(function(){
        $('.comment').keydown(function (e){
            if(e.keyCode == 13){
                var post_id = $(this).attr('post_id');
                var comment = $(this).val();
                $.post('/comment.php',{ post_id: post_id, comment:comment});
                $('.comment').val('');
/*i am guessing the problem starts from here and onwards*/
                $(this).parent().children('.comments').append("<div class='view_comment'><b>Username :</b>" + comment +"</div>");
            }
        });
    });

您应该添加e.preventDefault()以防止提交,因为当您在将自动提交表单的字段中单击输入button时:

if(e.keyCode == 13){
     e.preventDefault();
     var post_id = $(this).attr('post_id');
     var comment = $(this).val();
     ...
}

注意:输入是自闭标签之一,所以应该<input type="submit" id="post_button" />

希望这有帮助。

错误出在jQuery帖子中,我将其附加到..children('comments').append这是错误的,它应该是这样的

$(document).ready(function(){
    $('.comment').keydown(function (e){
        if(e.keyCode == 13){
            e.preventDefault();
            var post_id = $(this).attr('post_id');
            var comment = $(this).val();
            $.post('/comment.php',{ post_id: post_id, comment:comment});
            $('.comment').val('');
            $(this).parent().append("<div class='view_comment'><b>Username :</b>" + comment +"</div>");
        }
    });
});