2013-06-18 42 views
4

新來javascript。我知道這可能很簡單,但我無法弄清楚。我想執行一個函數。在函數中間暫停並等待用戶點擊「enter」鍵,這將允許函數再次繼續(或者將調用另一個函數來觸發)。暫停功能,直到輸入鍵被按下javascript

function appear() 
{ 
document.getElementById("firstt").style.visibility="visible"; 
//here is where I want the pause to happen until the user presses "enter" key 
//Below is what I want to happen after the "enter" key has been pressed. 
document.getElementById("startrouter").style.visibility="visible"; 


} 
+0

無法完成。抱歉。 –

+0

它可以做到。只是不在一個單一的方法。您將不得不將這個函數分解爲幾個部分,並且從Enter事件處理程序中執行延遲代碼。 –

+0

@尼克羅斯是的。這不是「暫停方法」,但是;-) –

回答

3

我會創建一個全局變量來查看javascript是否在等待按鍵。

在腳本的頂部,你可以在你的函數中添加

​​

然後將其設置爲true

function appear() 
{ 
    document.getElementById("firstt").style.visibility="visible"; 
    waitingForEnter = true; 
} 

然後......添加一個監聽回車鍵

function keydownHandler(e) { 

    if (e.keyCode == 13 && waitingForEnter) { // 13 is the enter key 
     document.getElementById("startrouter").style.visibility="visible"; 
     waitingForEnter = false; // reset variable 
    } 
} 

// register your handler method for the keydown event 
if (document.addEventListener) { 
    document.addEventListener('keydown', keydownHandler, false); 
} 
else if (document.attachEvent) { 
    document.attachEvent('onkeydown', keydownHandler); 
} 

我希望這有助於。這正是我想要做的,它可能不是最好的方法。

+1

你不似乎實際上使用'waitingForEnter' –

+1

謝謝我忘了添加它。 – Smeegs

+1

是的,我寧願使用jQuery處理綁定:-) –

1

或者我們可以從Javalsu內嵌解決方案,並擺脫全局變量。

function appear(){ 
    document.getElementById("firstt").style.visibility="visible"; 
    //here is where I want the pause to happen until the user presses "enter" key 
    function after(){ 
     //Below is what I want to happen after the "enter" key has been pressed. 
     document.getElementById("startrouter").style.visibility="visible"; 
    } 
    function keydownHandler(e) { 
     if (e.keyCode == 13 && waitingForEnter) { // 13 is the enter key 
      after(); 
     } 
    } 
    // register your handler method for the keydown event 
    if (document.addEventListener) { 
     document.addEventListener('keydown', keydownHandler, false); 
    } 
    else if (document.attachEvent) { 
     document.attachEvent('onkeydown', keydownHandler); 
    } 
}