【问题标题】:Hide all but $(this) via :not in jQuery selector通过 :not 在 jQuery 选择器中隐藏除 $(this) 之外的所有内容
【发布时间】:2010-11-22 15:13:29
【问题描述】:

高级标题,简单问题:

如何在 jQuery 中执行以下操作(隐藏除 $(this) 之外的所有内容)?

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

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

【问题讨论】:

    标签: jquery jquery-selectors this


    【解决方案1】:
    $(this).siblings().hide();
    

    Traversing/Siblings

    【讨论】:

      【解决方案2】:
      $("table.tr").not(this).hide();
      

      顺便说一句,我认为您的意思是 $("table tr")(用空格而不是点)。
      按照您的方式,它会选择每个具有tr 类的表(例如<table class="tr">),这可能不是您想要的。

      有关详细信息,请参阅documentation

      【讨论】:

      • 是的,点是一个错误。我不知何故看不到这比 Alexanders 的解决方案更容易,后者似乎更干净。我知道我问过如何使用 :not,但兄弟姐妹方法似乎更干净。
      • 只是添加,如果您单击表格中的某些内容以尝试隐藏所有表格行(不包括包含您单击的项目的行),请使用:$('tr').not($(this).closest('tr')).hide();
      • 这对于选择特定元素很有用,以防结构比同级允许的更复杂。我很难想出一个例子,但也许你想在网格中隐藏一些东西,而不是网格本身。
      【解决方案3】:

      如果你想把 not() 和其他一些选择器结合起来,你可以使用 add():

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

      这将淡出所有其他链接,但单击的链接除外,并且还会淡出一些选定的 id 和类。

      【讨论】:

        【解决方案4】:

        我认为解决方案可能是这样的:

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

        --编辑评论:

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

        【讨论】:

        • 你的意思是:not(#" + ...。此外,除非元素具有 ID,否则这将不起作用,这不太可能。
        • 这将要求您在所有表格行(或您正在使用的任何行)上添加随机和不必要的 ID。
        • @SLaks,感谢您的指正。在道琼斯指数中,您可能会想到,有时我们寻求的是提供快速答案来提供帮助。为什么不轻视我们的投入。
        • @nickf,是的,你是对的,但如果他们有每个 TR 的 ID,首先询问 @Kordonme 的评论会很好。
        猜你喜欢
        • 2016-01-11
        • 2023-04-05
        • 2016-08-14
        • 1970-01-01
        • 2014-12-10
        • 1970-01-01
        • 1970-01-01
        • 2015-05-09
        • 2017-03-28
        相关资源
        最近更新 更多