(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));
或者,我做错了吗?我该怎么办?
答案 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?
});
无论何时创建任何插件,都必须返回以保持可链接性。