jQuery $.fn.extend方式自定义插件

之前例子是扩展jQuery的工具方法,即通过$.xxx(para);的形式来使用的。下面是扩展jquery对象的方法,即任意一个jquery对象都已访问。

具体如下:

wyl.js:

 1 (function($){
 2     //访问方法: $('span p').siblings().chgColor();//所有祖先元素为span的p元素的相邻元素
 3     //作用:设置jquery对象的颜色
 4     $.fn.chgColor = function(colors){
 5         var tmpColor = colors;
 6         var flag = !(tmpColor);
 7         if(!(tmpColor)){
 8             // tmpColor = 'orange';
 9             tmpColor = '#93DDFF';//蓝色
10         }
11         if(typeof tmpColor!='string'){
12             alert('传入的参数必须是string型的');
13             return false;
14         }
15         
16         $(this).css('background',tmpColor);
17     }
18 })(jQuery)

html:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>无标题文档</title>
 6 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
 7 <script type="text/javascript" src="wyl.js"></script>
 8 <script>
 9 
10 $(function(){
11 
12     // $('div').next('p').css('background','red');
13     // $('span~p').chgColor();//查找span标记后所有同级的p标记
14     // $('span~p').chgColor();//查找span标记后所有同级的p标记
15     $('span p').siblings().chgColor();//所有祖先元素为span的p元素的相邻元素
16     // $('span').siblings('.haha').chgColor('orange');//找到span元素同级别元素中class为haha的元素
17     // $('span').siblings('div').chgColor('orange');//找到span元素所有同辈元素中 为 div元素的 元素
18 
19 });
20 
21 </script>
22 </head>
23 
24 <body>
25 <div>11111</div>
26 <p>11111</p>
27 
28 <div>22222</div>
29 <span>2222</span>
30 <p>22222</p>
31 <p class="haha">33333</p>
32 <span><p>44444</p><br><div>我是又一个div</div></span>
33 <div><p>我是div下的p元素</p></div>
34 <p>55555</p>
35 <p>6666</p>
36 </body>
37 </html>

效果:

原文地址:https://www.cnblogs.com/Sunnor/p/5617981.html