我在进度条上工作。它有一个标签。我想调整某个脚本完成后的标签。在找到可能解决方案的一些答案后,我想出了以下脚本。第一个启动并按预期工作。但是,第二个不是。它有什么问题?这是代码:
HTML:
<form method ="post">
<input class=generate type="submit" value="Upload" onclick="move();finalize()"/>
</form>
Javascript:
<script>
function move() {
var elem = document.getElementById("myBar");
var myFunc01 = function() {
var i = 1;
while (i < 101) {
(function(i) {
setTimeout(function() {
i++;
elem.style.width = i + '%';
elem.innerHTML = i + '%';
}, 600 * i)
})(i++)
}
};
myFunc01();
}
</script>
<script>
function finalize() {
var elem = document.getElementById("myBar");
var myFunc02 = function() {
elem.innerHTML = 'Finalizing...';
};
setTimeout(myFunc02, 600);
}
</script>
答案 0 :(得分:1)
var elem = document.querySelector('#myBar');
function done() {
elem.innerText = 'UPLOAD HAS FINISHED';
}
var upload = function(callback) {
var width = 1;
var id;
var frame = function() {
if (width >= 100) {
clearInterval(id);
callback();
} else {
width++;
elem.style.width = width + '%';
}
};
id = setInterval(frame, 10);
};
/*
upload(function() {
elem.innerText = 'UPLOAD HAS FINISHED';
});
*/
#myProgress {
width: 100%;
background-color: grey;
}
#myBar {
width: 1%;
height: 30px;
background-color: green;
text-align: center;
line-height: 27px;
}
<button onclick="upload(done)">START UPLOAD</button>
<div id="myProgress">
<div id="myBar"></div>
</div>
答案 1 :(得分:1)
您可以使用回调。回调是一个在完成时运行的函数。
function move(callback) {
//code you want to happen first
}
move(function(){
//code you want to have happen after completion
})
这就是简单回调如何运作的基本思路
答案 2 :(得分:0)
谢谢James,就是这样! 经过一些重新安排后,这就是第二个脚本的样子。它按预期工作。
<script>
function finalize() {setTimeout(function(){
var elem = document.getElementById("myBar");
var myFunc02 = function() {
elem.innerHTML = 'Finalizing...';
};
myFunc02();
}
, 600);}
</script>