如何在点击插件功能中保持可链接性?

时间:2014-02-10 05:41:14

标签: jquery

demo

(function(){
   $.fn.myFunc = function(s){
   var t = this, s = $(s);
      s.on('click',function(){
         t.toggle('slow');
      });
   };
}(jQuery));

$(document).ready(function($){
    $('#world')
     .myFunc('#hello')
     .css('background-color','blue');
     //css method is not chained. How to chain?
});

到目前为止我尝试了什么?

1

(function(){
   $.fn.myFunc = function(s){
   var t = this, s = $(s);

      s.on('click',function(){
         t.each(function(){
          t.toggle('slow');
         });
      });
   };
}(jQuery));

2

(function(){
   $.fn.myFunc = function(s){
   var t = this, s = $(s);
    t.each(function(){   
      s.on('click',function(){
          t.toggle('slow');
         });
      });
   };
}(jQuery));

或者,我做错了吗?我该怎么办?

4 个答案:

答案 0 :(得分:1)

您需要从插件返回元素集(this)以启用插件链接

(function () {
    $.fn.myFunc = function (s) {
        var t = this,
            s = $(s);
        s.on('click', function () {
            t.toggle('slow');
        });
        return this;
    };
}(jQuery));

演示:Fiddle

答案 1 :(得分:1)

您需要使用return this....

返回上下文

在你的情况下

(function(){
   $.fn.myFunc = function(s){
   var t = this, s = $(s);
      s.on('click',function(){
         t.toggle('slow');
      });
return t;
   };
}(jQuery));

答案 2 :(得分:0)

(function(){
   $.fn.myFunc = function(s){
   var t = this, s = $(s);
      s.on('click',function(){
         t.toggle('slow');
      });
       return this;
   };
}(jQuery));

最后使用返回此

答案 3 :(得分:0)

这是更新的代码。

(function(){
   $.fn.myFunc = function(s){
   var t = this, s = $(s);
      return s.on('click',function(){
         t.toggle('slow');
      });
   };
}(jQuery));

$(document).ready(function($){
    $('#world')
     .myFunc('#hello')
     .css('background-color','blue');
     //css method is not chained. How to chain?
});

无论何时创建任何插件,都必须返回以保持可链接性。

工作示例:http://jsfiddle.net/RwmpU/1/