插件没有按我的预期工作
我使用以下代码循环访问一组元素。
$(this).next().show().animate({top: '25px'},250,function(){
$(this).addClass('active');
});
但这是有限的,因为我需要到达元素列表的末尾,然后再次循环,所以我编写了这个插件:
(function($){
$.fn.extend({
rotater: function(class_check){
return this.each(function(){
if($(this).next().hasClass(class_check)){
return $(this).next();
} else {
return $(this).parent().children().first();
}
});
}
});
})(jQuery);
为了检测何时到达我想要的集合的末尾(它们都共享一个公共类) ),如果是这样,则抓住第一个对象以再次开始整个循环。
我将调用代码更改为:
$(this).rotater('common_class').show().animate({top: '25px'},250,function(){
$(this).addClass('active');
});
但它已完全停止工作!我很困惑,我可以理解我的“返回开始”脚本是否失败,但至少第一个周期的行为应该与 next()
完全相同,因为我实际上返回了 的值下一个()
。
我的 html 看起来像:
<div id="parent>
<div class="common_class"></div>
<div class="common_class"></div>
<div class="common_class"></div>
<div class="common_class"></div>
<div class="undesired_elemement"></div>
</div>
I was using the following code to cycle though a set of elements.
$(this).next().show().animate({top: '25px'},250,function(){
$(this).addClass('active');
});
but this was limited as I needed to get to the end of the list of elements, and cycle through again, so I wrote this plugin:
(function($){
$.fn.extend({
rotater: function(class_check){
return this.each(function(){
if($(this).next().hasClass(class_check)){
return $(this).next();
} else {
return $(this).parent().children().first();
}
});
}
});
})(jQuery);
In order to detect when I had reached the end of my desired set (which all share a common class) and if so, grab the first object in which to start the whole cycle again.
I changed the calling code to:
$(this).rotater('common_class').show().animate({top: '25px'},250,function(){
$(this).addClass('active');
});
but it has ceased to work entirely!! I am confused, I could understand if my "return to beginning" script failed, but at least the first cycle should behave exactly as next()
did, because I am literally returning the value of next()
.
My html looks like:
<div id="parent>
<div class="common_class"></div>
<div class="common_class"></div>
<div class="common_class"></div>
<div class="common_class"></div>
<div class="undesired_elemement"></div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
each
回调中的返回没有任何效果。您的旋转器函数返回each
返回的内容,这不是回调返回的内容,但它再次返回this
。解决方案:不要使用
each
:如果要将功能应用于选择器所选的所有元素,则只需使用
this.each
。如果选择了多个元素,您可能会遇到奇怪的行为。在这种情况下,您应该显式选择第一个元素:
The return in the
each
callback has no effect. Your rotator function returns whatevereach
returns, and that is not what the callback returns, but it returnsthis
again.Solution: Don't use
each
:You only have to use
this.each
if you want to apply a functionality to all elements the selector selected.You might experience weird behaviour though if more than one element is selected. In this case you should select the first element explicitly: