jQuery扩展

  • $仅仅是jQuery对象的一个别名。
  • 每次调用jQuery(),都会产生一个全新的jQuery对象,该对象继承了所有的内置的方法,这些方法都定义在$.fn对象中。
  • $.extends(target.obj1,obj2,...),它把多个object对象的属性和方法合并到一个target对象中,遇到同名属性时,总是使用靠后的对象的值,越后优先级越高。

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Test JQuery extends</title>
    <!--微软CDN-->
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
    <!--MyExtends.js与index.html在同一目录下-->
    <script type="text/javascript" src="MyExtend.js"></script>
</head>
<body>
    <h1 id="test1">Test1 Jquery Extends</h1>
    <h1 id="test2">Test2 jQuery Extends</h1>
    <h1 id="test3">Test3 jQuery Extends</h1>
    <h1 id="test4">Test4 jQuery Extends</h1>
    <h1 id="test5">Test5 jQuery Extends</h1>
</body>
</html>

MyExtend.js

//开启精确模式
'use strict';
$(document).ready(function(){
    //添加扩展方法1
    $.fn.modifyColor=function(options){
        //合并默认值与用户的设定值
        var opts=$.extend({},$.fn.modifyColor.defaults,options);
        this.css('backgroundColor',opts.bgColor).css('color',opts.color);
        //保证链式编程
        return this;
    };
    //要在添加了扩展方法之后,预设默认值
    $.fn.modifyColor.defaults={
        color:'white',
        bgColor:'black'
    };
    //Test1-预设的默认值
    $('#test1').modifyColor();
    //Test2-改变默认值
    $.fn.modifyColor.defaults={
        color:'yellow',
        bgColor:'blue'
    };
    $('#test2').modifyColor();
    //Test3-传参数代替默认值
    $('#test3').modifyColor({
        color:'red',
        bgColor:'green'
    });
    //添加扩展方法2
    jQuery.fn.extend({
      modifyBackGround1: function() {
        this.css('backgroundColor','red');
        return this;
      },
      modifyBackGround2: function() {
        this.css('backgroundColor','green');
        return this;
      }
    });
    //Test4
    $('#test4').modifyBackGround1();
    //Test5
    $('#test5').modifyBackGround2();
});

转载于:https://www.cnblogs.com/jiehuifang/p/7689234.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值