1

这是我的插件的代码..

$.fn.slide = function(settings) {

return $(this).each(function() {
    setInterval(function() { $.slider(opt.direction , opt.slideSpeed,this) }
}

jQuery.slider = function(direction,slideSpeed,elm) {
        console.log(elm) - > shows DOMWindow[] window as object 
    }

}


script.js   
$('#container').slide({
    slideAnimationTimeInterval : 6000,
    slideSpeed : 700,

}); 

console.log(elm) - > 将 DOMWindow[] 窗口显示为对象,但我需要#container 对象,我怎样才能得到它?

4

2 回答 2

4

嵌套函数时,您需要保存this在另一个变量中,如下所示:

return $(this).each(function() {
    var self = this;
    setInterval(function() { $.slider(opt.direction , opt.slideSpeed, self); }
}

this是函数的上下文,默认是全局对象window。jQuery 在调用函数时将其设置为更有用的东西(例如 中的元素.each())。但是,当您的区间函数被调用时,this将再次解除绑定 (=> this === window)。通过将其保存在自定义变量中,它会保存在函数的闭包中。

于 2012-04-17T09:48:45.943 回答
0

只需将其转换为 jQuery 对象:

var $elm = $( elm );
于 2012-04-17T09:48:51.347 回答