开发者

Parent selector in jquery

开发者 https://www.devze.com 2022-12-27 05:19 出处:网络
I have a table row that needs to be hidden when the anchor with class \"removerow\" is clicked. <tr><td>Product Name</td><td><a class=\"removerow\">Remove</a></

I have a table row that needs to be hidden when the anchor with class "removerow" is clicked.

<tr><td>Product Name</td><td><a class="removerow">Remove</a></td></tr>

I've been trying this, but it doesn't work:

$("a.removerow").click(function(){
$(tr > this).hide();

});

How can I select the entire table row with a child of ".removerow".

W开发者_JAVA百科hat am I doing wrong?

Thanks.


jQuery's closest(selector) function will traverse upward and return the nearest selector provided.

(If the element clicked is the same as the given selector, then it returns that.)

http://api.jquery.com/closest/

$("a.removerow").click(function(e){
    $(this).closest('tr').hide();
    e.preventDefault();
});

The e.preventDefault() will disable the default behavior of the a element.


jQuery doesn't have a parent selector, but it does have a parent function.

Also, the tr is not the direct parent of the link. Instead, it's two levels up (td is the first parent)

$("a.removerow").click(function(){
    // Called twice (first is td, second is tr)
    $(this).parent().parent().hide();
});

If there are no other trs in the hierarchy, you could also use

$("a.removerow").click(function(){
    // Called twice (first is td, second is tr)
    $(this).parents('tr').hide();
});

If the tr has a class on it, you could do this:

$("a.removerow").click(function(){
    // Called twice (first is td, second is tr)
    $(this).parents('.ClassNameHere').hide();
});
0

精彩评论

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