Debugging an XP bar

Debugging an XP bar

本文关键字:bar XP an Debugging      更新时间:2023-09-26

我一直在制作这段代码,但我似乎不能使它像我想要的那样工作。我想要一个提示,询问你在一个主题上工作了多长时间,然后在进度条上给出正确的宽度。

编辑: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>

您需要在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()的编写方式输入一个数字。

这段代码确保用户被要求提供一个有效的号码,直到他给出它。它也更干净一点。我删除了break,因为它不是一个有效的语法,如果你不在一个开关里面。

你可能想要删除代码中的超时,因为无论如何它都会在请求width之后被处理。从它里面清除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)
}