2016-07-25 84 views
0

我需要一个函数作为一个公共,所以我可以在任何jQuery选择器内调用它, 这里是代码。 注意:控制台说checkFeat fn没有定义。访问jquery选择器内的函数

(function checkFeat() { 
    $(".feat").each(function(){ 
     if (!$(this).hasClass("active")) { 
      $(this).children("P").css("display","none") 
     } 
     else 
     { 
      $(this).children("P").css("display","block") 
     } 
    });  
}()); 

$(".feat h5").on("click",function(){ 
    $(this).parent(".feat").addClass(function(index ,currentClass){ 
     checkFeat(); //console says this function is not defined why ?!! 
     return "active"; 
    }); 
}); 
+4

拆除包装和调用括号并调用它像你将任何正常功能。 – 2016-07-25 18:10:00

+0

这是正确的。自调函数不能从JavaScript中的任何其他地方调用。 – mhodges

+0

至于“为什么”,这是因为具有名称的函数*表达式将名称作用于函数本身的名称,所以它只能在该函数中使用。 – 2016-07-25 18:16:46

回答

2

在你的JavaScript文件,你可以这样写:

function checkFeat() { 
    $(".feat").each(function(){ 
     if (!$(this).hasClass("active")) { 
      $(this).children("P").css("display","none") 
     } 
     else 
     { 
      $(this).children("P").css("display","block") 
     } 
    });  
} 

$(".feat h5").on("click",function(){ 
    $(this).parent(".feat").addClass(function(index ,currentClass){ 
     checkFeat(); //console says this function is not defined why ?!! 
     return "active"; 
    }); 
}); 

这时如果要单独调用的函数,你可以简单地调用:

checkFeat(); 
+0

感谢兄弟它工作正常:) – Abdallah

0

你限制了checkFeat()closure内部,无法在封闭环境之外使用。删除它,一切都应该完美。

MDN JS DOCS

闭包是指独立的(自由)的变量 功能(即在本地使用的变量,但在一个封闭的范围所定义的)。 换句话说,这些功能'记住'它们创建的环境,其中 。

function checkFeat() { 
    $(".feat").each(function(){ 
     if (!$(this).hasClass("active")) { 
      $(this).children("P").css("display","none") 
     } 
     else 
     { 
      $(this).children("P").css("display","block") 
     } 
    });  
} 

$(".feat h5").on("click",function(){ 
    $(this).parent(".feat").addClass(function(index ,currentClass){ 
     checkFeat(); 
     return "active"; 
    }); 
});