发布于:使用 jQuery 核心

处理选择

link Getters & Setters(取值器与设置器)

一些 jQuery 方法可以用于对选中的元素进行赋值或读取某个值。当方法带一个值作为参数调用时,它被称为设置器(setter),因为它设置(或赋予)该值。当方法不带任何参数调用时,它获取(或读取)元素的值。设置器会影响选中的所有元素,而取值器(getter)仅返回选中的第一个元素所请求的值,但 .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" );

link Chaining(链式调用)

如果您对一个选择调用一个方法,并且该方法返回一个 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 而流行以来,许多库都采用了这一特性。然而,必须谨慎使用——过长的链式调用会使代码非常难以修改或调试。对于链式调用的长度没有硬性规定——只需知道很容易过度使用。