zl程序教程

您现在的位置是:首页 >  其它

当前栏目

jQuer链式调用的简单实现

实现 简单 调用 链式
2023-06-13 09:12:02 时间
在 jQuery 中,我们可以采用链式调用的方式来简化操作。其中,链式调用一般针对的是同一个 jQuery 对象。

举例:


 !DOCTYPE html 

 html 

 head 

 meta charset= utf-8 / 

 title /title 

 script src= js/jquery-1.12.4.min.js /script 

 script 

 $(function () {

 $( div ).mouseover(function(){

 $(this).css( color , red 

 $( div ).mouseout(function () {

 $(this).css( color , black 

 /script 

 /head 

 body 

 div C语言中文网 /div 

 /body 

 /html 

预览效果如图 1 所示。

链式调用
图 1:链式调用

分析:


$( div ).mouseover(function(){

 $(this).css( color , red 

$( div ).mouseout(function () {

 $(this).css( color , black 

})

上面代码,由于操作的都是$( div ),因此我们可以使用链式调用语法来简化代码,如下所示:


$( div ).mouseover(function(){

 $(this).css( color , red 

}).mouseout(function () {

 $(this).css( color , black 

})

在 jQuery 中,如果对同一个对象进行多种操作,则可以使用链式调用的语法。链式调用是 jQuery 中经典语法之一,不仅节省代码量,还可以提高网站的性能。

举例:


 !DOCTYPE html 

 html 

 head 

 meta charset= utf-8 / 

 title /title 

 style type= text/css 

 table, tr, td{border:1px solid silver;}

 width:40px;

 height:40px;

 line-height:40px;

 text-align:center;

 /style 

 script src= js/jquery-1.12.4.min.js /script 

 script 

 $(function(){

 $( td ).hover(function () {

 $(this).parent().css( background-color , silver 

 }, function () {

 $(this).parent().css( background-color , white 

 /script 

 /head 

 body 

 table 

 td 2 /td 

 td 4 /td 

 td 8 /td 

 /tr 

 td 16 /td 

 td 32 /td 

 td 64 /td 

 /tr 

 td 128 /td 

 td 256 /td 

 td 512 /td 

 /tr 

 /table 

 /body 

 /html 

默认情况下,预览效果如图 2 所示。

默认效果
图 2:默认效果

当鼠标指针移到某一个单元格上时,预览效果如图 2 所示。

鼠标指针移到单元格上时的效果
图 3:鼠标指针移到单元格上时的效果

分析:


$(this).parent().css( background-color , silver )

上面这句代码也用到了链式调用语法,其中$(this).parent()表示选取当前 td 元素的父元素(tr),然后再调用 css() 方法。

在使用链式调用语法时,为了照顾到代码的可读性,我们还可以把一行代码分散到几行来写,例如下面这样:


$( .content li )

 .removeClass( current )

 .eq(n)

 .addClass( current 

23918.html

CSSC语言htmljavaJavaScript