jQuery 对象绑定新方法(插件的实现)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-1.11.2.min.js"></script>
</head>
<body>
<div id="test-highlight1">
    <p>什么是<span>jQuery</span></p>
    <p><span>jQuery</span>是目前最流行的<span>JavaScript</span>库。</p>
</div>
<div id="test-external">
    <p>如何学习<a href="http://jquery.com">jQuery</a>?</p>
    <p>首先,你要学习<a href="/xxx/xxxx">JavaScript</a>,并了解基本的<a href="https://developer.mozilla.org/en-US/docs/Web/HTML">HTML</a>。</p>
</div>
<script type="text/javascript">
//    给jQuery对象绑定一个新方法是通过扩展$.fn对象实现的。让我们来编写第一个扩展——highlight1():
    $.fn.highlight1=function (options) {
        //函数内部的this在调用时被绑定为jQuery对象,所以函数内部代码可以正常调用所有jQuery对象的方法。
        var bgcolor = options && options.backgroundColor || '#fffceb';
        var color = options && options.color || '#d85030';
        this.css('backgroundColor', bgcolor).css('color', color);
//        this.css('backgroundColor','#93b300').css('color','#d85030');
        //为什么最后要return this;?
        //因为jQuery对象支持链式操作,我们自己写的扩展方法也要能继续链式下去:
        return this;
    };
$.fn.highlight = function (options) {
    // 合并默认值和用户设定值:
    var opts = $.extend({}, $.fn.highlight.defaults, options);
    this.css('backgroundColor', opts.backgroundColor).css('color', opts.color);
    return this;
}
// 设定默认值:
$.fn.highlight.defaults = {
    color: '#d85030',
    backgroundColor: '#fff8de'
}

    $('#test-highlight1 span').highlight1();

//最终,我们得出编写一个jQuery插件的原则:
//
//给$.fn绑定函数,实现插件的代码逻辑;
//插件函数最后要return this;以支持链式调用;
//插件函数要有默认值,绑定在$.fn.<pluginName>.defaults上;
//用户在调用时可传入设定值以便覆盖默认值。


//我们知道jQuery对象的有些方法只能作用在特定DOM元素上,比如submit()方法只能针对form。如果我们编写的扩展只能针对某些类型的DOM元素,应该怎么写?
//还记得jQuery的选择器支持filter()方法来过滤吗?我们可以借助这个方法来实现针对特定元素的扩展。
//举个例子,现在我们要给所有指向外链的超链接加上跳转提示,怎么做?
//先写出用户调用的代码:
$.fn.external = function () {
    // return返回的each()返回结果,支持链式调用:
    return this.filter('a').each(function () {
        // 注意: each()内部的回调函数的this绑定为DOM本身!
        var a = $(this);
        var url = a.attr('href');
        if (url && (url.indexOf('http://')===0 || url.indexOf('https://')===0)) {
            a.attr('href', '#0')
                    .removeAttr('target')
                    .append(' <i class="uk-icon-external-link"></i>')
                    .click(function () {
                        if(confirm('你确定要前往' + url + '?')) {
                            window.open(url);
                        }
                    });
        }
    });
}
</script>
</body>
</html>

版权声明:本文为darongzi1314原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。