2014-08-27 179 views
1

我正在學習一些基本的javascript,並想了解如何在某些條件滿足時返回到方法的開頭。使用if語句的條件循環

在這種情況下,用戶必須在提示中輸入一個字符才能進入「您輸入的字符爲」字符串。如果沒有輸入任何內容,我想實現一個循環來發送程序回到方法的開始。我有以下,迄今:

<script class="promptwindow">    
     var x 
     x = prompt("Please type a character in the box and click OK", "") 

     if (x = null) 
      {****} 

     document.write("The character you typed was ", x)  
</script> 

我不確定在****支架使用什麼,我需要類似的東西goto

編輯:是的,應該是==。我會在那裏留下錯誤,以便評論有意義。

+3

'''類= 「promptwindow」''的'''script'''標籤'? – onetwo12 2014-08-27 12:16:20

+3

no - >'if(x = null)'yes - >'if(x == null)' – 2014-08-27 12:17:31

回答

3

要回到你的函數開始,只需再次調用它:

<script type="text/javascript"> 
    (function myFunction() { 
     var x; 
     x = prompt("Please type a character in the box and click OK", "") 
     if (x === null) 
      myFunction(); 
     document.write("The character you typed was ", x); 
    })(); 
</script> 

要carreful到document.write()的位置,當x不會是空了,所有的堆疊document.write("The character you typed was ", x);將被執行

你也可以使用一個循環...

<script type="text/javascript"> 
    function myFunction() { 
     var x = null; 
     while(x === null || x === ""){ 
      x = prompt("Please type a character in the box and click OK", "") 
     } 
     document.write("The character you typed was ", x); 
    } 
</script> 
+2

'dw()'只執行一次... – Teemu 2014-08-27 12:21:52

+1

太棒了!我希望有這樣的事情+1。 – Wolfish 2014-08-27 12:22:09

+1

呃......實際上,現在它什麼也沒做。現在只是一個空白頁面。 – Wolfish 2014-08-27 12:25:56

1
<script type = "text/JavaScript"> 
    function UserInput(_callback_) 
    { 
     var value = ""; 
     do 
     { 
      value = prompt("Please type a sentence in the box and click OK", ""); 
     } 
     while(value === ""); 

     _callback_(value); 
    } 

    UserInput(function(text){ 
     document.write("The sentence you typed was { " + text + " }"); 
    }); 
</script> 

http://jsfiddle.net/dqda8Lgk/

我希望它會幫助你:)

+1

這有點更先進了,我今天晚些時候會看到回調。我欣賞片段,+1 – Wolfish 2014-08-28 09:41:18