2017-06-08 37 views
0

我試圖從提示框中獲取相同的值字符串,以便在onclick事件中運行該函數。 這種方式有可能嗎? 在此先感謝..js - 在onclick函數中調用body onload中的相同值

<!DOCOTYPE html> 
    <html> 
    <head> 
    </head> 
    <body onLoad = "h1();"> 

    <form> 
    <input type="button" value="function h3()" onClick="h3()"> 
    </form> 

    <script type="text/javascript"> 

     function h1(){ 
     var x = prompt(""); 
     console.log(x); 
     return h2(x); 
     } 

     function h2(str){ 
     console.log("get value from h1 function" + " " + str); 
     } 


     function h3(){ 
     console.log("return the value from h1 to h2"); 
     return h2(str); 

     } 
    </script> 
    </body> 
    </html> 

回答

0

你需要存儲的變量:

var answer;//store it in global scope 
function ask(){ 
    answer=prompt("a question"); 
} 

function h3(){ 
alert(answer || "no answer yet..."); 
} 

window.onload=ask; 

的內部函數的變量是垃圾回收函數返回時。因此,您需要將功能範圍中的變量移至全局範圍。那麼它的執着。

+0

非常感謝抱歉的noob問題 –