试图在 php while 循环中隐藏 jquery 中的特定 div

Trying to hide specific div in jquery in php while loop

我从 PHP while 循环中输出了这个表格:

echo '<div id="postCont" class="postCont'.$pid.'" style="block;">
    <div id="clLink">
      <a id="clLink" href="'.$plink.'" target="_blank"" title="'.$ptitle.'">'.$ptitle.'</a>
    </div>
    <div id="clDate">Posted on '.$pdate.'</div>
    <div id="clDesc">'.$pdesc.'</div>

    <form method="post" class="ibadForm">
        <input type="hidden" name="id" value="'.$pid.'">
        <input type="hidden" name="hiddenBad" value="yes">
        <input type="image" src="../img/bad.png" name="subBad" value="Bad" class="bad">
    </form>
</div>';

ibadForm 用 jquery 单击时,我试图删除个人 .postCont

$(".ibadForm").submit(function(e) {
     var url = "add_form.php"; 
     var id = <?php echo $pid?>;
     $.ajax({
          type: "POST",
          url: url,
          data: $(this).serialize(),
          success: function(data)
         {
             $('.postCont' + id).hide();
         }
     });
     e.preventDefault();
 });

它将表单提交给 add_form.php 正常,但没有隐藏 postCont。如果我从 class 中删除 id,那么它会隐藏所有 post 的续集。谁能告诉我哪里出错了?

您可以使用 closest() 获取父级 div 然后使用 hide() 方法隐藏它,例如:

$(".ibadForm").submit(function(e) {
  var url = "add_form.php"; 
  var id = <?php echo $pid?>;
  var _this = $(this);

  $.ajax({
    type: "POST",
    url: url,
    data: $(this).serialize(),
    success: function(data)
    {
      _this.closest('.postCont').hide();
    }
  });
  e.preventDefault();
});

注意: 您应该将引用单击的 form$(this) 对象存储在某个变量中(_this 在我的示例中)然后在成功回调中使用它,因为回调中的 $(this) 不再引用表单,例如:

_this.closest('.postCont').hide();

希望对您有所帮助。