简体   繁体   中英

jquery detecting and removing an element clicked

I have a hierachy of DIVs 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(); });

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.

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>
<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

$(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM