How to select this container element in jQuery

青春壹個敷衍的年華 提交于 2019-12-12 14:25:16

问题


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



来源:https://stackoverflow.com/questions/7111642/how-to-select-this-container-element-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!