我对progressbar有问题。我想在加载下一个函数后改变进度条。这是我的代码:
var tick=1;
var count=10;
function example(){
$('#progress div').css('width',(tick*count)+'%');
tick++;
}
$.when($.getJSON("data1.json",function(_a){data1=_a;})).done(function(){
example();
$.when(someLoadFunction).done(function(){
example();
$.when(someLoadFunction2).done(function(){
example();
//7 more...
});
});
});如何简化脚本,以便将来可以轻松扩展。
发布于 2016-10-14 17:58:43
创建一个要调用的函数数组,然后遍历这些函数。不是jQuery用户,因此可能有更有效的方法来实现这一点,但至少这是可合理维护的。或者就像@A.Wolff建议的那样。使用链接。
注意:如果你想在每个函数中使用不同的回调函数,可以使用function/callback将对象文字传递到函数中(在这种情况下不需要回调参数)。
$.when($.getJSON("data1.json", function(_a) {
data1 = _a;
})).done(function() {
var functionArr = []; //array of functions
loopWhen(functionArr, example());
});
function loopWhen(functionArr, callback) {
(var i = 0; i < functionArr.length; i++) {
$.when(functionArr[i]).done() {
callback();
};
};
};发布于 2016-10-14 18:41:55
您可以使用.queue()、.promise()、.then()。将函数存储在数组中,在解析当前函数承诺时,按顺序调用数组中的下一个函数。从返回jQuery promise对象,并将example用作.then()的函数参数
var tick = 0;
var count = 10;
var url = "https://gist.githubusercontent.com/"
+ "guest271314/23e61e522a14d45a35e1/"
+ "raw/a5ac6cffdc1ffab39f9db425844721b528751654/a.json";
// handle errors
function err(e) {
console.log(e)
}
function example(data) {
// do stuff
console.log(data);
$("#result").append(data + "<br><br>");
// return `.promise()`
return $("#progress div")
.css("width", (++tick * count) + "%")
.promise()
}
function progress(fn, next) {
return fn().then(example).then(next).fail(err)
}
// e.g., `someLoadFunction`, `someLoadFunction2`..
function someFunction() {
return $.Deferred(function(dfd) {
return dfd.resolve(tick)
})
}
// e.g., `$.getJSON()`, `someLoadFunction`, `someLoadFunction2`..
var arr = [
function() {return $.getJSON(url)}
, someFunction, someFunction, someFunction // `someLoadFunction2`..
, someFunction, someFunction, someFunction // `someLoadFunction5`..
, someFunction, someFunction, someFunction // `someLoadFunction8`..
];
$({}).queue("progress", $.map(arr, function(deferred) {
return $.proxy(progress, null, deferred)
})).dequeue("progress").promise("progress")
.then(function() {console.log("complete")});#progress div {
background: blue;
width: 0px;
height: 20px;
border: 2px solid green;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="progress">
<div></div>
</div>
<div id="result"></div>
https://stackoverflow.com/questions/40040083
复制相似问题