2016-04-23 41 views
0

我取的数据库的帖子用php while循环,这里是如HTML代码 - 的>如何选择独特的DIV ID和删除它

<div id="1"> content <button class="btn-primary" data-id="1">button</button></div> 
<div id="2">content 2 <button class="btn-primary" data-id="2">button</button></div> 

,如果有人点击第一个按钮,然后使用id = 1的div应去除

这里是jQuery代码

$(function() { 
    $("body").on("click", ".btn-primary", function() { 
     var ids = $(this).data('id'); // get data-id atrribute 
     var elements = this; 
     $('#id').remove(); // How can i remove the div by showing each id here 
     $.ajax({ 
      type: "POST", 
      url: "https://www.example.com/ajax, 
      data: "ids=" + ids, 
      success: function(data) { 
       setTimeout(function() { 
        $('.conner').append(data).fadeIn('slow'); 
       }, 2000); 
      } 
     }); 
    }); 
}); 

如何动态获取DIV ID和删除点击DIV

+5

'$( '#' + IDS)卸下摆臂();'?? –

回答

4

除非data-id持有多个值,您可以:

var ids = $(this).data('id'); // get data-id atrribute 
$('#' + ids).remove(); 

更简单的方式 - 被删除按钮父:

$(this).parent().remove(); 
+0

我想删除div div div id =“”not by data-id –

1

要么使用变量,如:

$('#'+ids).remove(); 

或者你可以只需跟着

$(this).parent().remove(); 
+0

我认为第二个选项是更好的选择。 –

+0

但是,当标记改变 - 它已经不是。 –

0

有时它的发生,如果一个元素的ID只包含电话号码,我们尝试访问该元素具有该ID的创建问题的国有企业更好地使用

$(this).parent().remove();

1

如果你的容器总是div你不需要使用你可以使用的ID:

$(this).closest('div').remove(); 

希望这会有所帮助。

0

如果要删除DIV的按钮后,除可以使用的直属母公司,

$(this).parent().remove(); 

如果你有层次比你可以添加.parent()多时间像

$(this).parent().parent().parent().remove(); 
0

有什么事情喜欢这个 ??

Codepen example

$(".button1").click(function() { 
    $(this).closest('.div1').fadeOut(500); 
}); 

HTML

<div class="div1">content1 
    <button class="btn-primary button1">button for div 1</button> 
</div> 
<div class="div1">content2 
    <button class="btn-primary button1">button for div 2</button> 
</div> 
<div class="div1">content3 
    <button class="btn-primary button1">button for div 3</button> 
</div> 
<div class="div1">content4 
    <button class="btn-primary button1">button for div 4</button> 
</div> 
<div class="div1">content5 
    <button class="btn-primary button1">button for div 5</button> 
</div>