首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一种jQuery插件的实现方法

一种jQuery插件的实现方法
EN

Stack Overflow用户
提问于 2013-01-31 05:49:54
回答 2查看 103关注 0票数 0

我正在尝试制作一个自定义复选框和单选按钮的jQuery插件。

代码语言:javascript
复制
(function($)
{
    $.fn.checkboxRadio = function(options)
    {
        var defaults = some;
        ...

        return this.each(function()
        {
            var button = $(this);
            ...
        });
    }
})(jQuery);

现在$('input').checkboxRadio(options);就可以使用它了

如何在不改变当前作用域的情况下添加方法check,以便尽可能地使用$('input').checkboxRadio('check')之类的东西

如何处理自定义方法并在我的插件中获得它的名称?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-31 06:12:15

这是官方的jquery plugin guide

有关包装函数的部分可以在here ("Plugin Methods")中找到(示例是一个潜在的工具提示插件):

代码语言:javascript
复制
(function( $ ){
  var methods = {
    init : function(options) { ... },
    show : function() { ... },
    hide : function() { ... },
    update : function(content) { ... }
  };

  $.fn.tooltip = function( method ) {

    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
  };
})(jQuery);

更新解释了指南中的methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ))行:

如果从javascript代码中调用$(selector).tooltip('update', 'hello'),您希望最终调用update方法,将'hello'作为content参数传递,并在调用期间将this设置为$(selector)

这就是这一行所要做的:

  • 如果method == 'update'methods[method]update方法,则['update', 'hello']将等于['update', 'hello'],则必须删除第一个元素以获取要传递给方法的参数;这正是Array.prototype.slice.call(arguments, 1)所做的,have调用函数myFunc,将argsArray作为参数传递,并在调用期间将<代码>D27设置为<代码>D28。<代码>H229<代码>F230

因此,在你的方法中,你可以调用this.each(...)来迭代所有选择器的项,例如:

代码语言:javascript
复制
update: function(content) {
  this.each(function(){ $(this).data('tooltip.content', content); });
  return this;
}
票数 1
EN

Stack Overflow用户

发布于 2013-01-31 06:09:04

你可以像这样连接插件方法:

代码语言:javascript
复制
(function($) {
    $.fn.checkboxRadio = function(options) {
        var defaults = {
            check: 'check'
    }

        return this.each(function() {
            var o = options;
            var _this = $(this);

            if( o.check === 'check' ) {
                 _this.attr('checked','checked');
            }else if ( o.check === 'uncheck' ) {
                 _this.removeAttr('checked');
            }
        });
    }
})(jQuery);

和用户文档应该是您想要的:$('input').checkboxRadio({check:'check'});

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14614484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档