您的位置:首页 > Web前端 > JQuery

jquery 拓展

2016-08-18 15:03 309 查看
1. 概述

jquery允许拓展自定义的方法, 绑定到$.fn对象上,

编写一个jQuery插件的原则:

$.fn
绑定函数,实现插件的代码逻辑;

插件函数最后要
return this;
以支持链式调用;    

插件函数要有默认值,绑定在
$.fn.<pluginName>.defaults
上;

用户在调用时可传入设定值以便覆盖默认值。

2. example

<html>
<body>
<div id="test-highlight1">
<p>什么是<span>jQuery</span></p>
<p><span>jQuery</span>是目前最流行的<span>JavaScript</span>库。</p>
</div>
<script src="jquery-3.1.0.js"></script>
<script type="text/javascript">
$(function(){
'use strict';

(function(){
$.fn.highlight = function (options) {

var opts = $.extend({}, $.fn.highlight.defaults, options);
// this已绑定为当前jQuery对象:
this.css('backgroundColor', opts.backgroundColor).css('color', opts.color);
return this;
}

$.fn.highlight.defaults = {
'backgroundColor' : '#d85030',
'color' : '#fff8de'
};

$.fn.highlight.defaults.backgroundColor = '#659f13';
$.fn.highlight.defaults.color = '#f2fae3';

$("#test-highlight1 span").highlight();

$('#test-highlight1 span').highlight({
color : '#dd1144'
});
})();
});

</script>

</body>
</html>


3.  使用过滤 针对特定元素的拓展

类似submit方法只能作用在form上,我们也可以自定义针对指定dom元素使用的方法。

jquery的filter这时派上了用场。

example

<html>
<body>
<div id="test-external">
<p>如何学习<a href="http://jquery.com">jQuery</a>?</p>
<p>首先,你要学习<a href="/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000">JavaScript</a>,并了解基本的<a href="https://developer.mozilla.org/en-US/docs/Web/HTML">HTML</a>。</p>
</div>
<script src="jquery-3.1.0.js"></script>
<script type="text/javascript">
$(function(){
'use strict';

(function(){
$.fn.external = function () {
return this.filter('a').each(function(){
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);
}
});
}

});

}

$('#test-external a').external();

})();
});

</script>

</body>
</html>


    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: