2013-07-08 98 views
0

我试图编写一个函数,当调用切换我的'p'标记。使用函数切换div与jQuery

我知道我可以使用

$(this).click(function(){ 
    // Run my function here 
}); 

但我想它作为一个功能,因此它可以被称为,我可以在多个项目中使用它。

任何人都可以看到我的错在哪里呢?

(function(toggle){ 
    $(this).on("click", function(){ 
     $(this).parent().find('p').slideToggle(); 
    }); 
}) 

下面的示例代码:http://jsfiddle.net/UBaSq/

+0

您还没有添加任何选择的单击处理 –

回答

3
toggler = function() { 
    $(this).parent().find("p").slideToggle(); 
} 

// someElement will be passed as "this" to toggler 
$("someElement").on("click", toggler); 

// Call toggler right away 
toggler.apply($("someElement")); 
+0

谢谢@Mishik,CAN我问,应用程序做了什么? – Liam

+1

'functionX.apply(obj,[arg1,arg2,...])'==用参数'arg1,arg2,...调用函数X并将'this'设置为'obj'。类似:'functionX.call(obj,arg1,arg2,...)'==同样适用,但你需要列出参数而不是通过数组提供它们。 – mishik

1

尝试

jQuery(function($){ 
    $('a').on("click", function(){ 
     $(this).parent().find('p').slideToggle(); 
    }); 
}); 

演示:Fiddle