【问题标题】:How to select by CSS styles in jQuery?如何在 jQuery 中通过 CSS 样式进行选择?
【发布时间】:2011-04-08 02:11:59
【问题描述】:

我正在尝试查找所有具有 CSS 样式 display:none 的父元素。我似乎无法让它工作。这是我得到的:

var $parents = $(...).parents("[css=display:none]");

【问题讨论】:

    标签: jquery css jquery-selectors


    【解决方案1】:

    如果您想要实际上 display: none; 的那些(可能包含 在另一个display: none; 中),您可以使用.filter().css()得到那些父母,像这样:

    var $parents = $(...).parents().filter(function() {
                      return $(this).css('display') == 'none';
                   });
    

    这会获取父级,然后过滤它们以仅获取 那个特定父级上的display: none;

    【讨论】:

      【解决方案2】:

      @Nick's solution 是一种实现目标的非常简单直接的方法。这也可能是性能最好的方法。但是,为了完整和方便(如果您经常这样做),也可以创建自己的选择器:

      $.expr[':'].css = function(obj, index, meta, stack) {
          var args = meta[3].split(/\s*=\s*/);
          return $(obj).css(args[0]) == args[1];
      }
      
      // Then we can use our custom selector, like so:
      $("#myElement").parents(":css(display=none)").show();
      

      示例 - http://jsfiddle.net/V8CQr/

      在以下位置查看有关创建自定义选择器的更多信息:

      http://www.jameswiseman.com/blog/2010/04/19/creating-a-jquery-custom-selector/

      【讨论】:

        【解决方案3】:
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title></title>
            <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
            <script type="text/javascript">
                $(document).ready(function () {
                    $('a').parents('div[style*="display: none"], [style*="display:none"]').show();
                });
            </script>
        </head>
        <body>
            <div class="Test" style="color: Red; display: none;">
                aaa <a href="#test">test</a><br />
            </div>
            <div class="Test" style="color: Aqua;">
                bbb <a href="#test">test</a><br />
            </div>
            <div class="Test" style="font-size: 15px; display: none;">
                ccc <a href="#test">test</a><br />
            </div>
        </body>
        </html>
        

        【讨论】:

          【解决方案4】:

          你很亲密:

          $(...).parents('[style*="display: none"]');
          

          注意:这会对元素属性值进行子字符串搜索,因此不如上面显示的$(this).css(...) 过滤器解决方案。

          docs

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-04-22
            • 2013-09-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多