2016-09-14 24 views
0

我一直在努力做這個代碼,但我似乎無法讓它像我想要的那樣工作。我想提出一個提示,詢問你在一個主題上工作了多長時間,然後在進度條上給出正確的寬度。調試一個XP吧

編輯:widthGenerator創建彈出窗口,但我似乎無法在widthGenerator()中將可變寬度轉換爲Move()作爲Move的寬度。

這裏是我的代碼:

<body class="w3-container"> 
<div class="w3-progress-container w3-round-xlarge"> 
    <div id="myBar" class="w3-progressbar w3-round-xlarge" style="width:1%"></div> 
</div> 

<button class="w3-btn" onclick="move()">Click Me</button> 

<script> 
function widthGenerator() { 
var question = prompt("Enter number of hours worked:", "Enter here"); 
    if (isNaN(question) == false) { 
     var width = (question * 2.33463); 
     break; 
    } else if (isNaN(question) == true) { 
    question = prompt("That is not a number; Enter the number of hours worked:", "Enter here"); 
    break; 
    }; 
} 
function move() { 
    var elem = document.getElementById("myBar"); 
    var id = setInterval(frame, 1); 
var width = widthGenerator() 
function frame() { 
    if (width >= widthGenerator()) { 
     clearInterval(id); 
    } else { 
     width += 0.1; 
     elem.style.width = width + '%'; 
    } 
    } 
} 
</script> 
+0

它以什麼方式不起作用?你有錯誤嗎?包括你的帖子中出現了什麼問題。 – dckuehn

+0

修正它以描述問題是什麼。 – Ian

回答

0

您需要在您的widthGenerator()函數return聲明:

function widthGenerator() { 

    var question = prompt("Enter number of hours worked:", "Enter here"); 
    if (!isNaN(Number(question))) { 
     var width = (question * 2.33463); 
    } else { 
     question = prompt("That is not a number; Enter the number of hours worked:", "Enter here"); 
    } 

    return width; 
} 

我不想擺弄太多與你的代碼,但請注意,有可能用戶不會根據寫入widthGenerator()的方式輸入數字。

+0

這會工作,但我有另一個問題是我將如何停止移動的寬度增量,所以它只能達到寬度的數量? – Ian

+0

有忘記包含的for循環嗎?通常增量和break語句表明for循環。此外,您的代碼似乎還有其他問題。我想你需要一個單獨的問題。我對上面這篇文章中的問題的回答似乎是正確的 –

+0

可能。謝謝! :d – Ian

0

此代碼確保用戶被要求輸入有效數字,直到他給出。它也有點乾淨。如果你不在交換機內部,我刪除了中斷,因爲它不是有效的語法。

您可能想要刪除代碼中的超時值,因爲無論如何,它都會詢問寬度後再執行。從裏面清理imeout不會做任何事情。最後,我刪除了函數框架,原因是1,它是爲每次調用move()而創建的,但其次,大多數情況下,由於您可以使用匿名函數執行此類工作,因此這種方法並不適用。

function widthGenerator() { 
    var question = prompt("Enter number of hours worked:", "Enter here") 
    while(isNaN(question)){ 
     question = prompt("That is not a number; Enter the number of hours worked:", "Enter here") 
     // this will make it loop, till the user gives a valid number 
    } 
    return (question * 2.33463) 
} 

function move() { 
    var elem = document.getElementById("myBar") 
    var width = widthGenerator() 

    // You don't really need the timeout, since you can make the if anyway. 
    var id = setInterval(function(){ 
     // this is anonymous function, it is used if you need to pass a callback to 
     if (width >= widthGenerator()) { 
      // Clearing this timeout won't do anything as you allready did cleared it by calling it 
      clearInterval(id) 
     } else { 
      width += 0.1 
      elem.style.width = width + '%' 
     } 
    }, 1) 
} 

隨時問任何問題。