Javascript Jquery删除问题div仍然存在

Javascript Jquery删除问题div仍然存在,javascript,php,jquery,html,ajax,Javascript,Php,Jquery,Html,Ajax,昨天我用PHP、HTML和ajax编写了一个Commentbox。ajax部分让我有机会在不刷新页面的情况下删除评论。我这样做的方式是,我通过数据库给每个注释(div)一个唯一的id。例如,在我的mysql数据库中,注释是这样的: Username: blabla<br> Comment: haha this is so funny<br> id: 52 这在删除第一条注释时效果很好。但是它不允许我删除其他注释,除非我刷新页面>。deleteComment是的子元素,看

昨天我用PHP、HTML和ajax编写了一个Commentbox。ajax部分让我有机会在不刷新页面的情况下删除评论。我这样做的方式是,我通过数据库给每个注释(div)一个唯一的id。例如,在我的mysql数据库中,注释是这样的:

Username: blabla<br>
Comment: haha this is so funny<br>
id: 52

这在删除第一条注释时效果很好。但是它不允许我删除其他注释,除非我刷新页面>
。deleteComment
子元素,看起来您需要首先从父元素获取id,然后针对您单击的子元素,在ajax请求返回成功后隐藏注释:

$(".deleteComment").click(function(){
    var id = $(this).parent().attr("id");
    var child = $(this);
    $.ajax({
        type: 'GET',
        url: 'deletecomment.php',
        data: "id=" + id,
        success: function(){
            child.hide();
            // or if you want to delete the entire element with the id of X
            // child.parent().hide();
        }
    });
});

文档就绪事件中的代码仅在第一次单击时才能正常工作。为了完成这项工作,必须在标记中注册一个点击事件。 例如:

<div class="deleteComment" onclick="DeleteMe(id)">Delete the comment here!</div>
</div>

function DeleteMe(id)
{
  $.ajax{

          Type: 'GET',
          url: 'deletecomment.php',
          data: "id=" + id,
          success: function(){

               $("#" + id).hide();

           }


          }

        });
  }
删除此处的评论!
函数DeleteMe(id)
{
$.ajax{
键入:“GET”,
url:'deletecomment.php',
数据:“id=”+id,
成功:函数(){
$(“#”+id).hide();
}
}
});
}

如果在div上单击不起作用,您可以使用锚定标记(此处删除)。

代码中需要做的更改很少

首先,将ID标记添加到内部div

<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment" id="<?php echo $commentid; ?>">Delete the comment here!  </div>
</div>
而不是

id = $(".deleteComment").attr("id");
第三,更改ajax调用,如下所示:

$(document).ready(function(){

$(".deleteComment").click(function(){


 //Getting the id of comment

 id = $(".deleteComment").attr("id");

$.ajax{

Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){

 $("#" + id).hide();

 }


 }

});

});
$.ajax({
        Type: 'GET',
        url: 'deletecomment.php',
        data: "id=" + id
    }).done(function(){
        $("#" + id).hide();
    });

如果不只是回复我,希望这对您有效。

您的意思肯定是
$(this).parent().attr(“id”)
?缺少('after the$.ajax.Im抱歉各位。这里的代码非常混乱,但我的文档中的语法是正确的。函数正在工作,但问题是它只删除一条注释。
变量id没有var关键字,这使得它是全局的
。毫无理由地污染全局命名空间是个坏主意。
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment" id="<?php echo $commentid; ?>">Delete the comment here!  </div>
</div>
id = $(this).attr("id");
id = $(".deleteComment").attr("id");
$.ajax({
        Type: 'GET',
        url: 'deletecomment.php',
        data: "id=" + id
    }).done(function(){
        $("#" + id).hide();
    });