【问题标题】:Can jQuery select by CSS rule, not class?jQuery 可以通过 CSS 规则而不是类来选择吗?
【发布时间】:2010-09-07 19:40:30
【问题描述】:

一个.container 可以包含许多.components,而.components 本身可以包含.containers(而.containers 又可以包含.components 等)

给定这样的代码:

$(".container .component").each(function(){
  $(".container", this).css('border', '1px solid #f00');
});

我需要在大括号内的行中添加什么以仅选择嵌套的.containers,它们的 CSS 中的 width 设置为 auto?我确信这很简单,但我并没有真正使用过 jQuery。

【问题讨论】:

  • 非常感谢您的回复。理想情况下,我希望在选择器中包含 CSS 规则,这样我就有一组 .component 中的所有 .containers 具有 CSS 宽度:auto,但没关系。

标签: javascript jquery css-selectors


【解决方案1】:

您可能想查看.filter()

类似:

$('.container .component .container')
.filter(function() {return $(this).css('width') == 'auto';})
.css({border: '1px solid #f00'});

【讨论】:

    【解决方案2】:
    $(".container .component").each(function()
    {
        $(".container", this).each(function() {
            if($(this).css('width') == 'auto')
            {
                $(this).css('border', '1px solid #f00');
            }
        });
    });
    

    与其他答案类似,但由于组件也可以有多个容器,因此也需要 .each() 在此处检查宽度。

    【讨论】:

      【解决方案3】:
      $(".container .component").each(function() {
          if ($(".container", this).css('width') === "auto")
              $(".container", this).css('border', '1px solid #f00');
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-30
        • 1970-01-01
        • 1970-01-01
        • 2012-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多