2014-01-29 118 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 
}