How to select this container element in jQuery

2019-07-04 11:59发布

问题:

I having trouble to select the currently clicked container element.

My Html

<div class="cparent">
foo1
<a href="javascript:void(0);" class="delete">Delete</a>
</div>

<div class="cparent">
foo2
<a href="javascript:void(0);" class="delete">Delete</a>
</div>

I mean when I click on delete link, corresponding container should disappear. How can I do this?

What I tried !

$(".cparent",this).html('Deleting...').delay(1000).fadeOut();// not working

My script

$(".delete").live("click",function(){
 var cur = $(".delete").index(this);
 $(".cparent").eq(cur).html('Deleting...').delay(1000).fadeOut();
 });

Above one is also not working. Have a look at this Example for clarification.

回答1:

Use the parent[API Ref] method:

$(this).parent().html('Deleting...').delay(1000).fadeOut();

Passing this as the second parameter to the jQuery function won't find elements that are above this. Alternatively, you can use the closest[API Ref] method:

$(this).closest('.cparent').html('Deleting...').delay(1000).fadeOut();


回答2:

use closest to select the immediate parent

$(".delete").live("click",function(){
 var cur = $(this);
 cur.closest("div.cparent").html('Deleting...').delay(1000).fadeOut();
 });

here is the fiddle http://jsfiddle.net/szVKD/10/

jquery closest



回答3:

$('div.cparent').click (function (e)
{
    if ($(e.target).attr ('class') == 'delete')
    {
        $(this).html('Deleting...').delay(1000).fadeOut();
    }
}
);

fiddle here



回答4:

Try using the parent():

$(this).parent().html('Deleting...').delay(1000).fadeOut();

You can see it working here:

http://jsfiddle.net/gchoken/YFMZW/1/



回答5:

The approach you are using seems to be a bit more complex than it needs to.

Try using this as your handler, it is more precise and easier to read:

$(this).parent(".cparent").html('Deleting...').delay(1000).fadeOut();