发布在:使用 jQuery Core

使用选择

链接 获取器和设置器

某些 jQuery 方法可用于分配或读取选择中的某些值。当使用值作为参数调用该方法时,它被称为设置器,因为它设置(或分配)该值。当不带参数调用该方法时,它获取(或读取)元素的值。设置器影响选择中的所有元素,而获取器仅为选择中的第一个元素返回请求的值,但 .text() 除外,它会检索所有元素的值。

1
2
// The .html() method sets all the h1 elements' html to be "hello world":
$( "h1" ).html( "hello world" );
1
2
3
// The .html() method returns the html of the first h1 element:
$( "h1" ).html();
// > "hello world"

设置器返回一个 jQuery 对象,允许您继续对选择调用 jQuery 方法。获取器返回它被要求获取的任何内容,因此您无法继续对获取器返回的值调用 jQuery 方法。

1
2
3
// Attempting to call a jQuery method after calling a getter.
// This will NOT work:
$( "h1" ).html().addClass( "test" );

链接 链式调用

如果您对选择调用一个方法,并且该方法返回一个 jQuery 对象,则您可以在不暂停分号的情况下继续对该对象调用 jQuery 方法。这种做法被称为“链式调用”。

1
$( "#content" ).find( "h3" ).eq( 2 ).html( "new text for the third h3!" );

在多行中中断链条可能有助于提高代码可读性。

1
2
3
4
$( "#content" )
.find( "h3" )
.eq( 2 )
.html( "new text for the third h3!" );

jQuery 还提供了 .end() 方法,用于在您在链条中间更改选择时返回到原始选择。

1
2
3
4
5
6
7
$( "#content" )
.find( "h3" )
.eq( 2 )
.html( "new text for the third h3!" )
.end() // Restores the selection to all h3s in #content
.eq( 0 )
.html( "new text for the first h3!" );

链式调用非常强大,并且自 jQuery 使其流行以来,许多库都采用了此功能。但是,必须谨慎使用它——广泛的链式调用会使代码极难修改或调试。对于链条应该有多长没有严格的规则——只要知道很容易被冲昏头脑即可。