【问题标题】:What is the purpose of the second argument in $(first, second) [duplicate]$(first, second) 中第二个参数的目的是什么 [重复]
【发布时间】:2013-01-30 22:20:56
【问题描述】:

可能重复:
What does the second argument to $() mean?

有一段时间我使用 jQuery,有时我会看到:

$(argument1, argument2).doSomething();

使用第二个参数进行过滤的文档在哪里?

编辑:

我说的是这种使用方式:

var t=0; // the height of the highest element (after the function runs)
var t_elem;  // the highest element (after the function runs)
$("*",elem).each(function () {
    $this = $(this);
    if ( $this.outerHeight() > t ) {
        t_elem=this;
        t=$this.outerHeight();
    }
});

注意:

$("*",elem)

我不是在说

$("a,b,span")

过滤方式。我现在很好。

【问题讨论】:

标签: jquery


【解决方案1】:

这是jQuery() documentation中的第一个定义:

jQuery( selector [, context ] )

   selector
      Type: selector
      A string containing a selector expression

   context
      Type: Element, jQuery
      A DOM Element, Document, or jQuery to use as context

再往下:

选择器上下文

默认情况下,选择器从文档根目录开始在 DOM 中执行搜索。但是,可以使用$() 函数的可选第二个参数为搜索提供替代上下文。

但是,它在内部只调用.find,您经常会发现人们建议使用.find 而不是传递第二个参数。

所以,你的例子相当于$(argument2).find(argument1).doSomething();

【讨论】:

  • +1 用于 .find() 内部 - 很多人不知道这一点
【解决方案2】:

文档位于 jQuery API 文档right here.

双参数语法有三种风格:

$( selector [, context ] )

将选择器的范围限定为context 元素的子元素。这是您发布的示例代码中使用的变体。 selector 应用于context 节点的后代节点。

还有:

$( html [, ownerDocument ] )

从提供的原始 HTML 字符串动态创建 DOM 元素。

最后::

$( html, [, attributes ] )

其中定义了创建 DOM 元素的指定属性、事件和方法来调用新创建的元素。

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 2016-03-25
    • 2011-10-22
    • 2010-11-11
    相关资源
    最近更新 更多