2012-03-24 37 views
1

我正在写一个jQuery插件,这与此类似,jQuery的,如果在一个不同的功能

$(this).each(function(){ 
    $el = $(this).find('.el') 
    $el.click(function(){ 
     test(); 
    }); 
    function test() { 
     console.log('test init'); 
    } 
}); 

$el点击

这正常使用,但是当我使用未定义功能在test()$el.click外面这样

$(this).each(function(){ 
    $el = $(this).find('.el') 
    test(); 
    function test() { 
     console.log('test init'); 
    } 
}); 

我得到错误类型undefined is not a function

PS:我在咖啡,语法/拼写编码是不是这里的问题

+1

因为...'测试()'还没有确定,当它被称为? JS执行lineraly,就像“从上到下”。尝试在声明下移动测试,并告诉我它是否可行。 – Joseph 2012-03-24 07:52:00

+0

我看,谢谢,那么最好的办法是保持整个代码下面的功能,但仍然激活它?因为将顶级功能带入一个大块看起来会很丑陋。 – devric 2012-03-24 07:53:55

+0

准确测试尚未定义,当您设置.click事件绑定时,它可以正常工作;另外如果我可能会问为什么你要在.each循环中保存函数定义?只是好奇!希望这会有所帮助,欢呼 – 2012-03-24 07:55:17

回答

2

如果您test()需要立即执行,那么这样做:

$(this).each(function(){ 
    $el = $(this).find('.el') 

    (function test() { 
     console.log('test init'); 
    }());       //the "()" at the end executes the function 
}); 

test()won't be available from the outside world这办法。它有点“封闭”。如果你需要测试立即执行,仍然是被别人调用,这样做:

$(this).each(function(){ 
    $el = $(this).find('.el') 

    var test = (function testFunc() { 
     console.log('test init'); 
     return testFunc;    //return itself to the variable "test" 
    }());        //execute 
}); 
+2

对于最后一种情况,你也可以去'var test = function(){[...]};试验();'。 – huon 2012-03-24 07:58:03

+0

@dbaupp我认为,但如果你有一个同时是一个声明的立即调用的表达式,它会“看起来更干净”。 – Joseph 2012-03-24 08:00:05