javascript jquery 检测并删除单击的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5299895/
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 detecting and removing an element clicked
提问by Shahid Karimi
I have a hierachy of DIVs with classes associated but not IDs. How can I remove the item being clicked?
我有一个 DIV 的层次结构,其中包含关联的类但没有关联的 ID。如何删除被点击的项目?
<div>
<div class="minibox" onclick="remove_me()">Box1</div>
<div class="minibox" onclick="remove_me()">Box1</div>
<div class="minibox" onclick="remove_me()">Box1</div>
<div class="minibox" onclick="remove_me()">Box1</div>
<div class="minibox" onclick="remove_me()">Box1</div>
</div>
<script>
function remove_me(){
///remove the clicked div
}
</script>
回答by gion_13
$('div .minibox').click(function(e){
$(e.target).remove();
});
回答by JaredMcAteer
$('.minibox').click(function() { $(this).remove(); });
回答by Martin Jespersen
Change
改变
<div class="minibox" onclick="remove_me()">Box1</div>
to
到
<div class="minibox" onclick="remove_me(this)">Box1</div>
then use
然后使用
<script>
function remove_me(elm){
$(elm).remove();
}
</script>
回答by Geoff Appleford
Inside the jQuery document.ready()event, you need to bind a click handler to the div's
在 jQuery document.ready()事件中,您需要将一个单击处理程序绑定到div的
$(document).ready(function() {
$('.minibox').click(function(e){
$(this).remove();
});
});
Check out jQuery remove()and click().
The thisinside the event handler refers to the element that was clicked on.
this事件处理程序的内部是指被点击的元素。
回答by Kon
回答by Mark Coleman
回答by meo
your html:
你的html:
<div class="box">some content</div>
<div class="box">some content</div>
<div class="box">some content</div>
<div class="box">some content</div>
ect...
your jQuery
你的jQuery
$(function(){ //make sure your DOM is ready
$("div.box").click(function(){ // bind click on every div that has the class box
$(this).remove(); //remove the clicked element from the dom
});
});
Demo with fadeOut animation: http://jsfiddle.net/qJHyL/1/(and fancy delete icon)
带有淡出动画的演示:http: //jsfiddle.net/qJHyL/1/(和花哨的删除图标)
回答by balexandre
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<div class="box">Box 4</div>
<div class="box">Box 5</div>
then you would use
那么你会使用
$(".box").bind("click", function() {
$(this).fadeOut(500, function() {
// now that the fade completed
$(this).remove();
});
});
Example in JSBIN

