jquery detecting and removing an element clicked
I have a hierachy of DIV开发者_如何学Pythons with classes associated but not IDs. How can I remove the item being clicked?
<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>
$('div .minibox').click(function(e){
$(e.target).remove();
});
$('.minibox').click(function() { $(this).remove(); });
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>
Inside the jQuery document.ready() event, you need to bind a click handler to the div
's
$(document).ready(function() {
$('.minibox').click(function(e){
$(this).remove();
});
});
Check out jQuery remove() and click().
The this
inside the event handler refers to the element that was clicked on.
$(document).ready(function() {
$('.minibox').click(function () {
$(this).remove();
});
});
Check out remove().
If you can use jQuery to register your event it is as easy as:
$(".minibox").click(function(){
$(this).remove();
});
Code example on jsfiddle.
your 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
$(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)
<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
精彩评论