jQuery - 使用要点 - 同被选择元素一起工作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013275171/article/details/85313989

同被选择元素一起工作

取得值、设置值:一些jQuery的方法可以同时被用于分配和设定被选择者的一些值。这些方法在呼叫时,若传入参数值,那么其会设定被选择者的值;若未传入参数值,那么其会取得被选择集中的第一个被选择者的值。Setters会影响所有被选择元素的值,而Getters只会返回选择集中第一个被选择者的值。例外的是:.text()方法会取得元素的所有值。

// <h1>jQuery</h1>

// .html()方法设置所有<h1>元素的值为:"hello world"
$( "h1" ).html( "hello world" );

// .html()方法返回<h1>元素的值
$( "h1" ).html();
// 返回值为:"hello world"

Setter模式,会返回一个jQuery对象,可以使用此对象继续呼叫其他的jQuery方法;而Getter模式,会返回被选择者的html值,不能继续用来调用其他的jQuery方法。

// 可以正常工作
$( "h1" ).html("Hello World").addClass( "test" );

// 不会正常工作
$( "h1" ).html().addClass( "test" );

方法链:若被选择者呼叫的jQuery方法会返回jQuer对象,那么可以继续使用点标来呼叫其他的jQuery方法。方法链使用的弊端是难以修改和跟错。

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

// 更佳的可读性
$( "#content" )
    .find( "h3" )
    .eq( 2 )
    .html( "new text for the third h3!" );

jQuery同时提供.end()方法,用以在方法链中返回到原始的选择集中。

$( "#content" )
    .find( "h3" )
    .eq( 2 )
        .html( "new text for the third h3!" )
        .end() // 还原到#content中所有的<h3>元素集#content
    .eq( 0 )
        .html( "new text for the first h3!" );

猜你喜欢

转载自blog.csdn.net/u013275171/article/details/85313989