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

具体如下:

wyl.js:

 (function($){
//访问方法: $('span p').siblings().chgColor();//所有祖先元素为span的p元素的相邻元素
//作用:设置jquery对象的颜色
$.fn.chgColor = function(colors){
var tmpColor = colors;
var flag = !(tmpColor);
if(!(tmpColor)){
// tmpColor = 'orange';
tmpColor = '#93DDFF';//蓝色
}
if(typeof tmpColor!='string'){
alert('传入的参数必须是string型的');
return false;
} $(this).css('background',tmpColor);
}
})(jQuery)

html:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="wyl.js"></script>
<script> $(function(){ // $('div').next('p').css('background','red');
// $('span~p').chgColor();//查找span标记后所有同级的p标记
// $('span~p').chgColor();//查找span标记后所有同级的p标记
$('span p').siblings().chgColor();//所有祖先元素为span的p元素的相邻元素
// $('span').siblings('.haha').chgColor('orange');//找到span元素同级别元素中class为haha的元素
// $('span').siblings('div').chgColor('orange');//找到span元素所有同辈元素中 为 div元素的 元素 }); </script>
</head> <body>
<div>11111</div>
<p>11111</p> <div>22222</div>
<span>2222</span>
<p>22222</p>
<p class="haha">33333</p>
<span><p>44444</p><br><div>我是又一个div</div></span>
<div><p>我是div下的p元素</p></div>
<p>55555</p>
<p>6666</p>
</body>
</html>

效果:

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

04-25 08:03