2017-10-14 54 views
0

在我的JavaScript程序中,我在do-while循環中創建了提示對話框。提示應該運行直到用戶在提示中進入停止。當用戶在提示中輸入值時,它應該顯示在屏幕上,並且應該生成另一個提示。但在我的情況下,當我第一次輸入值提示時,會生成另一個提示而不顯示值。任何人都可以告訴我我的代碼有什麼問題嗎?JavaScript:如何在每次提示後顯示值

代碼:

<html> 
<head> 
    <title>lab12</title> 
</head> 
<body bgcolor="#efe862"> 
    <h3 id="txt1"></h3> 
</body> 
<script> 
    myFunction(); 
    function myFunction() { 
     do { 
      var prom = window.prompt("Enter a text(stop to exit)"); 
     } while(prom != "stop");  
     document.getElementById("txt1").innerHTML = "The text is: " + prom; 
    } 
</script> 
</html> 
+0

我裏面加做的,但仍然無法正常工作 – pari

回答

0

你有兩個問題:

  1. 的代碼,以顯示它是外循環
  2. 即使是在循環中,你沒有給瀏覽器提供它的機會。

試試這個:

function myFunction() { 
 
    var prom = window.prompt("Enter a text (cancel to exit)"); 
 
    if (prom != null) { 
 
     document.getElementById("txt1").innerHTML = "The text is: " + prom; 
 
     setTimeout(myFunction, 0); 
 
    } 
 
} 
 
myFunction();
<h3 id="txt1"></h3>

setTimeout功能將產生控制瀏覽器,因此它可以呈現文本,再次調用myFunction之前。

+0

太感謝你了,但是當我進入停止它不應該顯示提示...它應該打印上次和退出。 – pari

+0

是的,我發現非常討厭,而選擇只是點擊取消,而不是。我相信你可以想出如何讓它停止在「停止」,而不是,如果這是你真正想要的。 – glennsl

+0

我很抱歉,你覺得它很煩人。我用do/while並使用了setTimeout,但它仍然不起作用。請介意編輯代碼嗎? – pari

-1
<script type="text/javascript" language="javascript"> 
     myFunction(); 

     function myFunction() 
     { 
     var prom = ""; 
     var done = false; 

     try 
      { 
      while(!done) 
      { 
       prom = window.prompt("Enter a text(stop to exit)"); 

      if(prom==null) prom="null"; 

      done = (prom.toLowerCase() =="stop"); 

      if(!done) document.getElementById("txt1").innerHTML = "The text is: " + prom; 
      }  
     } 
     catch(e) 
      { 
     alert("Error: " + e.Message); 
      } 
      finally 
      { 

      } 
    } 
</script> 
+0

它不工作 – pari

+0

哎呀...猜測它應該是「.toLowerCase()」 – codemaker

+0

也許這將更好地工作 – codemaker

-1

這應該工作,而不是顯示dom中由於提示而隱藏的答案,這會將文本置於下一個提示中。

<script> 
function myFunction(){ 
var prom=prompt("Enter some text"); 
while(prom!="stop"){ 
prom=prompt("The text is "+prom); 
} 
} 
myFunction(); 
</script> 
+0

你可以讓它運行嗎? – pari

+0

它不起作用。 – pari

+0

我剛測試過它,它對我有用,什麼不工作? – user7951676