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?
因为一旦它进入return 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");
...
});
});
};
return 之后放也没什么作用:
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"之前,我也不知道是否可以在函数内放置return"范围之外的任何内容(对我来说似乎无效?):
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 个元素,但通常会有比 1 个更多的 div.
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屋!