Hide all but $(this) via :not in jQuery selector

2019-01-12 21:55发布

Advanced title, simple question:

How can I do the following in jQuery (hiding everything except $(this))?

$("table tr").click(function() {
    $("table tr:not(" + $(this) + ")").hide();
    // $(this) is only to illustrate my problem

    $("table tr").show();
});

4条回答
The star\"
2楼-- · 2019-01-12 22:33
$("table.tr").not(this).hide();

As an aside, I think you mean $("table tr") (with a space instead of a dot).
The way you have it, it selects every table which has a class of tr (eg, <table class="tr">), which is probably not what you want.

For more information, see the documentation.

查看更多
干净又极端
3楼-- · 2019-01-12 22:34
$(this).siblings().hide();

Traversing/Siblings

查看更多
乱世女痞
4楼-- · 2019-01-12 22:36

I think a solution can be this:

$("table.tr").click(function() {
    $("table.tr:not(" + $(this).attr("id") + "").hide(); // $(this) is only to illustrate my problem
    $(this).show();
})

--EDIT for Comment:

$("table.tr").click(function() {
    $("table.tr:not(#" + $(this).attr("id") + ")").hide(); // $(this) is only to illustrate my problem
    $(this).show();
})
查看更多
Explosion°爆炸
5楼-- · 2019-01-12 22:40

If you want to combine not() with some other selectors, you can use add():

$('a').click(function(e){
  $('a').not(this).add('#someID, .someClass, #someOtherID').animate({'opacity':0}, 800);
});

This would fadeout all other links, but the clicked one, and additionally fadeout some chosen ids and classes.

查看更多
登录 后发表回答