100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > [Js/Jquery]jquery插件开发

[Js/Jquery]jquery插件开发

时间:2020-06-09 04:42:11

相关推荐

[Js/Jquery]jquery插件开发

摘要

上篇文章简单学习了js自调用方法。今天就趁热打铁,学一学怎么编写一个jquery插件。

JQuery

参考地址:/playerlife/archive//05/11/2495269.html

通过JQuery.fn增加一个新的函数来编写JQuery插件,也可以说是在Jquery对象上面扩展一个新的方法。

代码片段:

jQuery.fn.myPluigin = function () {//code...};

似乎这样就可以了,但有个问题,也许你的扩展的方法会和jquery中的方法产生冲突,所以这时候最好用一个 自执行的函数将其包裹起来,并且将JQuery作为参数传进去。所以有了下面的代码:

(function ($) {$.fn.myPluigin = function () {//code... };})(jQuery);

通过这种方式,由于闭包的关系,所以和其它地方的并不会产生冲突。

一个简单插件

获取页面上div的最大宽度

<script>(function ($) {$.fn.maxWidth = function () {var max = 0;//this 指向的是jquery对象this.each(function () {//this指向DOM元素,要取到这个dom元素,可以通过$(this)max = Math.max(max, $(this).width());});return max;};})(jQuery);var maxWidth = $("div").maxWidth();console.log(maxWidth);</script>

链式

为了使用jquery中链式开发的特性,所以在封装插件的时候,需要返回这个元素供链条上的下一个使用。

(function ($) {$.fn.Chain= function (type) {//this 指向的是jquery对象return this.each(function () {var $this = $(this);if (type && type == "width") {$this.width($this.width());}});};})(jQuery);$("div").Chain("width").css("color", "red");

因为该插件返回了this,所以你可以继续链式,比如 css()。如果你的插件如果不是返回一个简单值,你通常应该返回this。

默认值选项

在使用插件的过程中,经常可以看到插件有部分的默认值,我们只需传入需要替换的参数即可,就可以对插件进行配置。

(function ($) {$.fn.myAlert = function (options) {var settings = {"location": "top","background-color": "red"};console.log('default', settings);return this.each(function () {if (options) {$.extend(settings, options);console.log('extend', settings);};});};})(jQuery);$("div").myAlert({ "location": "center" });

结果

在这个例子中,使用插件后,默认的location被替换为center,而background-color保持原样。这样可以保证高度可配置醒,而不需要开发者定义所有可能的选项了。

命名空间

命名空间的重要性,可以保证你的插件不被其他插件重写,也能避免被页面上其它代码重写。

注意

在任何情况下都不压迫在一个插件中为jQuery.fn增加多个方法。

(function ($) {$.fn.method1 = function () {};$.fn.method2 = function () {};..$.fn.methodn = function () {};})(jQuery);

可以这样,将方法放在一个对象里面,然后根据不同的参数进行调用:

(function ($) {var methods = {method1: function (options) { },method2: function () { },};$.fn.myMethod = function (method) {if (methods[method]) {return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));} else {//.... }}})(jQuery);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。