2016-07-25 6 views
0

私は任意のjqueryセレクタの中で呼び出すことができるように、関数をpublicにする必要があります。 ここにコードがあります。 注:コンソールはcheckFeat fnが定義されていないと言っています。jqueryセレクタ内の関数にアクセスする

あなたの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"; 
    }); 
}); 
+4

ラッピングを外し、括弧を起動し、任意の通常の関数のと同じようにそれを呼び出します。 –

+0

それは正しいです。 javascriptのどこからでも自己呼び出し関数を呼び出すことはできません。 – mhodges

+0

"理由"については、名前付きの関数*式*が名前自体を関数本体にスコープするため、その関数内でのみ使用できるためです。 –

答えて

2

、あなただけ書くことができます。

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"; 
    }); 
}); 
関連する問題