$(this).each(jquery插件中的function()返回DOM []对象而不是此对象

时间:2012-04-17 09:47:19

标签: jquery

这是我插件的代码..

$.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对象如何才能获得它?

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:0)

只需将其转换为jQuery对象:

var $elm = $( elm );
相关问题