如何使用jquery处理php循环通过元素

How to handle php loop through elements with jquery

本文关键字:元素 循环 php 何使用 jquery 处理      更新时间:2023-09-26

我有一个HTML表单,在插入查询成功后,它将以HTML格式返回JQueryAjax。

comment.php

$post_id=$_POST['id'];
 mysql_query("INSERT INTO comment(comment,post_id,)VALUES('$comment','$post_id')");
if(!mysql_errno()){
?>
<p><?php echo $comment; ?></p>

这是我的JQuery代码,它将发送请求和值,并在插入查询成功后返回HTML表单。

index.php

// on post comment click 
    $('.bt-add-com').click(function(){
        var theCom=$(this).siblings('.the-new-com');
        if(!theCom.val()){ 
            alert('You need to write a comment!'); 
        }else{
        var post_id=$(this).parents(".post_id").attr("id");
            $.ajax({
                type: "POST",
                url: "comment.php",
                data: "act=add-com&comment="+theCom.val()+"&id="+post_id,
                success: function(html){
                    theCom.val('');
                    $('.the-new-com').hide('fast', function(){
                        $('.new-comment-line').show('fast');
                        $('.new-comment-line').after(html);  
                    });
                }  
            });
        }
    });

这是我的表单。它在用户每次提交的帖子循环中运行。

<form action="" method="POST" class="post_id" id="<?php echo $post_id; ?>">
    <span>Write a comment ...</span>
    </div>
    <div class="new-comment-line"></div><----here is a line before the comment initiates..--->
        <textarea class="the-new-com"></textarea>
        <div class="bt-add-com">Post comment</div>
</form>

现在我的问题是,除了JQuery代码的最后几行之外,我的所有代码都运行得很好。

$('.new-comment-line').after(html);

Ajax请求出现问题后,我的表单从comment.php返回HTML表单时的代码行。每当用户提交状态时,在每一篇帖子中,表单都会打印出来。

我应该如何处理表格?我希望每次只在用户提交的特定帖子中打印我的评论。

显然$('.new comment line')是一个类选择器,您要选择这个类中的所有元素。当你通过点击按钮开始你的功能时,我建议选择相对于点击按钮的正确元素。因此,点击按钮后,立即选择正确的元素:

var correctElement=$(this).siblings('.new-comment-line');

然后在需要时将html添加到其中:

correctElement.after(html);