javascript jQuery 删除 div onclick
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16287152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery remove div onclick
提问by Sideshow
I can't seem to get my jQuery right to remove a div when I delete something
当我删除某些内容时,我似乎无法让我的 jQuery 正确删除 div
Code is:
代码是:
<div class="amend_order" data-item_key="1367264719mz7">
<p>Home Made Ice Cream</p>
<p class="small_text">Pistachio</p>
<p>
<a class="edit_item ui-link" href="javascript:void(0);">Edit</a>
----
<a class="deleter ui-link" href="javascript:void(0);">Delete</a>
</p>
</div>
I have tried using
我试过使用
$(this).closest('div').remove();
unfortunately this does not work.
不幸的是,这不起作用。
Basically there is a list of several divs
and I just want them to disappear when clicked.
基本上有一个列表,divs
我只希望它们在单击时消失。
回答by Ian
If your container divs are dynamically added, you need to use event delegation. Try this:
如果您的容器 div 是动态添加的,则需要使用事件委托。试试这个:
$("#container").on("click", ".amend_order .deleter", function () {
$(this).closest("div").remove();
});
DEMO:http://jsfiddle.net/m6jVP/
演示:http : //jsfiddle.net/m6jVP/
If they're added dynamically, then the event binding won't actually find any elements and therefore won't execute when they're clicked. This event handling runs for any elements inside of #container
that match the selector .amend_order .deleter
when they are clicked.
如果它们是动态添加的,那么事件绑定实际上不会找到任何元素,因此在单击它们时不会执行。当单击它们时#container
,此事件处理会针对与选择器匹配的任何元素运行.amend_order .deleter
。
You can replace #container
with a selector that matches a stable (static) element containing these divs you're targeting, using document
if necessary.
您可以替换为#container
与包含您定位的这些 div 的稳定(静态)元素匹配的选择器,document
如有必要,请使用。
回答by Nedudi
HTML
HTML
<div class="amend_order" data-item_key="1367264719mz7">
<p>Home Made Ice Cream</p>
<p class="small_text">Pistachio</p>
<p>
<a class="edit_item ui-link" href="javascript:void(0);">Edit</a>
----
<a class="deleter ui-link" href="javascript:void(0);">Delete</a>
</p>
</div>
JS
JS
$('.deleter').on('click', function(){
$(this).closest('div').remove();
})
Live sample http://jsfiddle.net/Ny346/
回答by Simone Pessotto
Try this:
试试这个:
$('.deleter').on('click', function(){
$(this).parent().parent().remove;
})
回答by DextrousDave
Try pointing to the div:
尝试指向 div:
$('div.amend_order').click(function(){
$(this).remove();
});
or when clicking on the delete button:
或单击删除按钮时:
$('a.deleter.ui-link').click(function(){
$(this).parent('div').remove();
});