如何在jquery中按按钮删除div

如何在jquery中按按钮删除div,jquery,button,draggable,Jquery,Button,Draggable,我试图解决jquery的可拖动问题,有一些代码可以从数据库中检索信息,每个信息都显示在数据库每一行的每个框中 “可拖动”可以正常工作,在拖动“删除”框时也可以正常工作 每个div-box都带有一个名为“remove”的按钮,该按钮用于移除单个div-box(不是同时移除所有div-box)。问题是,按下按钮移除每个单独的div框并没有移除,只是允许我移除第一个框而不是其余的框。请查看jquery代码,因为您可以看到它所说的行 $(this).closest('.draggable').remo

我试图解决jquery的可拖动问题,有一些代码可以从数据库中检索信息,每个信息都显示在数据库每一行的每个框中

“可拖动”可以正常工作,在拖动“删除”框时也可以正常工作

每个div-box都带有一个名为“remove”的按钮,该按钮用于移除单个div-box(不是同时移除所有div-box)。问题是,按下按钮移除每个单独的div框并没有移除,只是允许我移除第一个框而不是其余的框。请查看jquery代码,因为您可以看到它所说的行

 $(this).closest('.draggable').remove();
这条线坏了

任何其他想法,我如何解决这个问题,让我使删除按钮的工作

下面是php代码

<?php
include('dbcon.php');

$product_id=$_POST['selector'];
$N = count($product_id);
for($i=0; $i < $N; $i++)
{
 $result = mysql_query("SELECT * FROM product where product_id='$product_id[$i]'");
 while($row = mysql_fetch_array($result))
   { ?>
      <div class="draggable" id="draggable[]" style="width:300px; height:200px">
   <div class="thumbnail">
      <div id="remove"><a class="button" href="#"><span class="search-icon">remove</span></a></div>
 <div class="control-group">
    <label class="control-label" for="inputEmail">product id</label>
    <div class="controls">
  <input name="member_id[]" type="hidden" value="<?php echo  $row['product_id'] ?>" />
 <input name="firstname[]" type="text" value="<?php echo $row['product_name'] ?>" />
    </div>
    </div>

 <div class="control-group">
    <label class="control-label" for="inputEmail">product category</label>
    <div class="controls">
 <input name="lastname[]" type="text" value="<?php echo $row['product_category'] ?>" />
    </div>
    </div>

 <div class="control-group">
    <label class="control-label" for="inputEmail">product price</label>
    <div class="controls">
 <input name="middlename[]" type="text" value="<?php echo $row['product_price'] ?>" />
    </div>
    </div>
 </div></div>

 <br>

   <?php 
   }
}

?>

由于id是唯一的,所以您需要对
div
使用类

<div class="remove"><a class="button" href="#"><span class="search-icon">remove</span></a></div>
因此,基本上,这种技术将帮助您将click处理程序附加到这些新添加的
。在您的案例中删除
div元素

每个div框都带有名为“移除”的按钮

正如我看到的,您使用的是
#remove
,这基本上是错误的,因为ID必须是唯一的

比你的jQ看起来更像:

$('#parentElement').on('click', '.remove', function(){
    $(this).closest('.draggable').remove();
});

使用事件委派来动态创建元素(如果需要的话……但只是以防万一……)

谢谢您的回复,事件委派对我来说是新的,我刚刚了解到,甚至我尝试过,仍然不在这里工作是我放置$(document).ready(function(){$('#parentElement')。on('click','.remove',function(){event.preventDefault();$(this.closest('.draggable').remove();});});这是正确的!不,你的HTML没有任何id为
parentElement
的元素。你需要使用
最接近的静态父元素。删除
div或像我的回答一样使用
body
。嗨,我不明白为什么我还不熟悉它,请查看小提琴看看我出了什么问题……你需要使用
body
而不是
.remove
$('body')。在('click','remove',function(event){
。这里是最新的提琴:非常感谢演示,效果非常好,我想我还有很长的路要走,因为只有一个词('body')。再次感谢您的帮助。
$('body').on('click', '.remove' , function(){
    $(this).closest('.draggable').remove();
});
$('#parentElement').on('click', '.remove', function(){
    $(this).closest('.draggable').remove();
});