【发布时间】:2015-01-13 18:07:39
【问题描述】:
我正在尝试开发我的第一个 jQuery 插件。基本上,它将类附加到站点上的各种元素,然后在用户滚动时更改它(我正在计算偏移量等等)。而且我想我已经碰到了这个问题。
这是我启动插件的方式:
$("div").myPlugin();
来源:
$.fn.myPlugin = function() {
return this.each(function() {
$(this).addClass("something-" + i);
i++;
});
};
有人可以解释一下如何在我的插件中使用 $(window).scroll 吗?
因为一旦它进入“return this.each”,它就会被附加到这个循环中的元素数...
$.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 之后放也没什么作用:
$.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”范围之外的任何内容(对我来说似乎无效?):
$.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。
非常感谢。
【问题讨论】:
标签: jquery jquery-plugins return