【问题标题】:Confine all jQuery selectors to children of a specific element将所有 jQuery 选择器限制为特定元素的子元素
【发布时间】:2011-05-09 15:36:38
【问题描述】:

我当然知道如何在每次进行选择时将 jQuery 选择器限制为特定元素的子元素(即 $('#left ul') 选择所有属于 #left 的子元素的 ul)。虽然这很简单,但如果我要对#left 的各个子节点执行一堆操作,则必须继续编写 $('#left ul')、$('#left p')、 $('#left ...').相反,我更愿意暂时将潜在的选择器限制为#left 的唯一子级。例如:

...some code that established #left as the "scope" of any future selectors;
$('ul').css(...); //actually selects $('#left ul')
$('p').css(...); //actually selects $('#left p')

...some code that re-established the full DOM as the "scope";
$('ul').css(...); //selects all ul, not just children of #left
$('p').css(...); //selects all p, not just children of #left

谢谢!

【问题讨论】:

    标签: javascript jquery dom css-selectors


    【解决方案1】:

    只需依赖上下文并找到。

    var $l = $('#left')
      , ul = $l.find('ul')
      , p = $l.find('p');
    

    【讨论】:

    • 其实你的 l 变量已经是一个jQuery对象了。所以你可以说 ul = l.find('ul')。无需重新包装。
    • 我知道这一点,但并不总是出现在我的答案中。
    • 感谢您的回复。但这并没有真正加快编码过程。现在你只是被困在每次都写 $l.find(...) 而不是 $('#left ...') 每次。知道哪个更快吗?我猜是 $('#left ...'),但我并没有基于太多:)
    • l.find('ul') 比 $('#left ul') 甚至 $('#left').find('ul') 更快(假设你已经找到 l)因为您不必再​​次查找#left 元素。
    • 如果 meder 的答案不是您想要的,您能否澄清您的问题?正如 Adilson 所提到的,您始终可以将上下文指定为第二个参数。这就是你要找的东西吗?
    【解决方案2】:

    “$”方法可以接收 2 个参数:选择器和上下文。因此,您可以使用以下语法:

    $('.children_selector',$('.the_parent_selector'))
    

    但是,为了避免使用 $(selector,context)。您可以编写一个函数,“覆盖” $ 函数,然后在其中编写代码。看看:

                (function($)
                {
                    //here the $ selects the elements inside the first element with the class xpto
                })(function(a){return $(a,$('.xpto')[0]);});
    

    无论如何,我不喜欢找到这种结构。出于维护目的,获得更多的代码行比获得更少的晦涩代码行更好。

    【讨论】:

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