jQuery插件开发-返回this.each问题 [英] jQuery plugin development - return this.each issue
问题描述
我正在尝试开发我的第一个jQuery插件.基本上,它将类添加到站点上的各种元素,然后在用户滚动时进行更改(我正在计算偏移量和其他内容).而且我想我已经碰到了这堵墙.
I'm trying to develop my first jQuery plugin. Basically it appends classes to various elements on site an then changes it when user scrolls (I'm calculating offsets and whatnot). And I think I've hit a wall with this one.
这是我启动插件的方式:
Here's how I start the plugin:
$("div").myPlugin();
来源:
$.fn.myPlugin = function() {
return this.each(function() {
$(this).addClass("something-" + i);
i++;
});
};
有人可以解释一下如何在我的插件中使用$(window).scroll吗?
Could someone explain please how to use $(window).scroll in my plugin?
因为一旦它返回this.each",它就会被附加与该循环中的元素一样多的次数...
Because once it into "return this.each" it gets attached as many times as many elements there are in this loop...
$.fn.myPlugin = function() {
return this.each(function() {
$(this).addClass("something-" + i);
i++;
$(window).scroll( function() { <!-- here it not only attaches itself x-times but i is always the same -->
...
$(".something-" + i).addClass("active");
...
});
});
};
在返回后将其放入不会做任何事情:
Putting it after return doesn't do nothing:
$.fn.myPlugin = function() {
return this.each(function() {
$(this).addClass("something-" + i);
i++;
});
$(window).scroll( function() { <!-- doesn't seem to work -->
...
$(".something-" + i).addClass("active");
...
});
};
在没有"i"之前,我也不知道是否可以在函数内的返回"范围之外放置任何东西(对我来说似乎无效吗?):
And before there are no "i"s, also I don't know if I can put anything outside of the "return" scope inside a function (doesn't seem valid to me?):
$.fn.myPlugin = function() {
$(window).scroll( function() { <!-- there is no "i" yet -->
...
$(".something-" + i).addClass("active");
...
});
return this.each(function() {
$(this).addClass("something-" + i);
i++;
});
};
我是jQuery的新手,不确定我是否正确理解了文档,我想知道是否完全不使用return可能更好吗?请注意,此插件可以使用1个元素,但通常div会大于1.
I'm new to jQuery and I'm not sure if I understand the documentation correctly, I was wondering wether it might be better to do not use return here at all? Note this plugin can work with 1 element but usually there will be more divs than 1.
非常感谢.
推荐答案
这是怎么回事:
(function($, window, undefined){
$.fn.myPlugin = function() {
// bind the scroll event listener once
$(window).scroll(function(){
console.log('scroll');
});
// iterate your plugin elements
// use index passed by the .each callback:
this.each(function(i, el){
$(el).addClass('something-' + i);
});
// return your jQuery object to allow chaining on your plugin
// note that (this instanceof jQuery) === true, so there is no need
// to pass it to the jQuery function i.e. $(this)
return this;
};
})(jQuery, window);
$('div').myPlugin();
console.log($('div').map(function(){ return this.className; }).get());
http://jsfiddle.net/yw0q5hn7/2/
这篇关于jQuery插件开发-返回this.each问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!