开发者

jquery detecting and removing an element clicked

开发者 https://www.devze.com 2023-02-16 13:49 出处:网络
I have a hierachy of DIV开发者_如何学Pythons with classes associated but not IDs. How can I remove the item being 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号