gpt4 book ai didi

javascript - jQuery 轮播 "this"上下文未传递到 .animate 回调中

转载 作者:行者123 更新时间:2023-11-28 09:05:26 25 4
gpt4 key购买 nike

我正在滚动自己的轮播代码(以此处 http://www.queness.com/post/923/create-a-simple-infinite-carousel-with-jquery 的精彩文章为蓝本),但在传递“this”选择器上下文时遇到问题,但仅限于 slider.animate() 内。初始 .before() 与 $("ul.slides li:first", this) 和 $("ul.slides li:last", this) 选择器一起使用,因为它位于 .animate() 之外。

我有一个这样声明的 jQuery 插件:

$.fn.promoSlider = function(opts) {
$(this).data('initialized', true);

var speed = 400;
var item_width = 274.5;
var left_value = item_width * (-1);

var slider = $("ul.slides", this);

//'this' works
$("ul.slides li:first", this).before($("ul.slides li:last", this));
slider.css({'left' : left_value});

$('.btnprev', this).click(function() {
var left_indent = parseInt(slider.css('left')) + item_width;

slider.animate({'left' : left_indent}, speed, function() {
//'this' does not work
$("ul.slides li:first", this).before($("ul.slides li:last", this));
slider.css({'left' : left_value});
});
return false;
});

$('.btnnext', this).click(function() {
var left_indent = parseInt(slider.css('left')) - item_width;

slider.animate({'left' : left_indent}, speed, function() {
//'this' does not work
$("ul.slides li:last", this).after($("ul.slides li:first", this));
slider.css({'left' : left_value});
});
return false;
});
}

然后我初始化我的轮播并将“this”传递给插件,如下所示:

        $('.carousel').each(function() {
if($(this).data('initialized') !== true) {
$(this).promoSlider();
}
});

选择器上下文“this”在 .animate() 中丢失,并且不允许我将“this”传递到匿名回调函数中。因此 $("ul.slides li:first", this).before($("ul.slides li:last", this));永远不会得到解决,但只能在 .animate() 事件中得到解决。

任何帮助将不胜感激。预先感谢您查看此内容。

最佳答案

试试这个方法:

是的,动画中的this内容将是 slider 的内容。因此,您可以将上下文设置为另一个变量并在回调中访问它。

 var $this = this; //Set up the context to a variable here
slider.animate({'left' : left_indent}, speed, function() {
$("ul.slides li:first", $this).before($("ul.slides li:last", $this)); // access it.
slider.css({'left' : left_value});
});

您还可以使用$.proxy将回调函数设置为特定上下文。

slider.animate({'left' : left_indent}, speed, $.proxy(function() { //Set up the proxy for callback
$("ul.slides li:first", $this).before($("ul.slides li:last", $this)); // access it.
slider.css({'left' : left_value});
},this)); //Set the context. now withinthe animate callbnack this will refer to the context you pass here.

关于javascript - jQuery 轮播 "this"上下文未传递到 .animate 回调中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17181333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com