2014-01-29 117 views
0

在一個非常長的函數中,我需要在繼續執行腳本之前獲取用戶選項。JavaScript調用子函數並從函數內部返回

的想法是像這樣的東西來獲得已選定的值( 'A' 或 'B'):

function myMainFct { 

    // a lot of lines here 

    if(a_Defined_Value_Is_Ok) { var option="a"; } 

    else { 
     var choose = "<a onclick=\"myOption('a')\">A</a><a onclick=\"myOption('b')\">B</a>"; 
     // here I put the <a> choices in a div 

     // now the subfunction 
     function myOption(x) { return x; } 

     // what will happen when I'll get the value 
     if (x) { var option=x; } 
    } 

    if (option=="a") { 
     // let's continue the script for users with "a" option 
    } 

    else if (option=="b") { 
     // let's continue the script for those with "b" option 
    } 

    // end of common main function 
} 

回答

0

與你的語法保持:

var x = (function myOption(x) { return x; })(); 
+0

對不起,它不起作用。 if(x)alert(x)沒有任何反應:-( –

+0

var x =(function myOption(x){alert(x); return x;})();發送警報「Undefined」,然後點擊 –

0

你需要將選項處理代碼放在一個單獨的函數中。

function myMainFct { 

    // a lot of lines here 

    if(a_Defined_Value_IsOk) 
    myCompletion("a"); 

    else { 
    var choose = "<a onclick=\"myCompletion('a')\">A</a><a onclick=\"myCompletion('b')\">B</a>"; 
    // here I put the <a> choices in a div 

    } 
    // end of common main function 
} 

function myCompletion(option) { 

    if (option=="a") { 
    // let's continue the script for users with "a" option 
    } 

    else if (option=="b") { 
    // let's continue the script for those with "b" option 
    } 

} 
+0

感謝您的回答但我需要在主函數中繼續使用腳本,因爲如果(a)或如果(b)在函數 –

+0

中進一步調用其他條件...所有這些都可能發生在繼續函數中,您可以在main函數中定義完成函數作爲函數變量('var myCompletion = function(option){...}'),在這種情況下,它可以訪問所有主函數的變量,否則,希望能夠在異步事件(點擊)後繼續執行這個功能,而這只是不會發生的。 –

+0

好吧,讓我們來試試吧:) Thx –

0

我終於找到了另一種解決方案。這不是最好的,但它的工作原理。

function myOption(x) { myMainFct(x); } // return to main function when called 

function myMainFct(x) { 

    // a lot of lines here 

    if(a_Defined_Value_Is_Ok) { var option="a"; } 

    else { 
    var choose = "<a onclick=\"myOption('a')\">A</a><a onclick=\"myOption('b')\">B</a>"; 
    // here I put the <a> choices in a div 

    if (x) { var option=x; } 
    } 

    if (option=="a") { 
    // let's continue the script for users with "a" option 
    } 

    else if (option=="b") { 
    // let's continue the script for those with "b" option 
    } 

    // end of common main function 
}