javascript - jQuery - $.post 延迟对象数组的协调事件处理程序
问题描述
我有一个$.each
块,它遍历a 上select
的所有元素,并为每个元素form
调用 a 。$.post
var deferredObjects = [];
$('#form').find('select').each(
function(i, o) {
var jqxhr = $.post("data.json", {} ));
deferredObjects.push( jqxhr) ;
}
);
我希望在所有发布操作完成后触发事件处理程序。我将从 post 方法返回的所有延迟对象收集到一个数组中。我希望使用类似的东西
$.when( ... ).then( ... );
但我看不到如何将这个构造融入我的场景?
解决方案
您可以使用 jquery 中可用的 promise()(一旦完成所有集体操作,它将执行)。例如,您可以看到
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>promise demo</title>
<style>
div {
height: 50px;
width: 50px;
float: left;
margin-right: 10px;
display: none;
background-color: #090;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
$( "button" ).on( "click", function() {
$( "p" ).append( "Started..." );
$( "div" ).each(function( i ) {
$( this ).fadeIn().fadeOut( 1000 * ( i + 1 ) );
});
$( "div" ).promise().done(function() {
$( "p" ).append( " Finished! " );
});
});
</script>
</body>
</html>
https://jsfiddle.net/mzo5Lhbk/
另外,如果您想使用 when() https://api.jquery.com/jquery.when/ ,请阅读这些链接
希望对你有帮助!!!
推荐阅读
- cmake - CLion 中的 CMake 版本未更新
- bash - 无法将 sed 命令的输出存储到变量中
- python-2.7 - 如何使用python代码在字符串上实现ROT13来演示字符串加密?
- google-sheets - 如何将数据移动到 Google 表格中的右侧空单元格?
- cognos - 按计数 ID 排序柱形图
- python - Docker 和 fcntl OSError Errno 22 无效参数
- javascript - 没有 WebPack 无法添加任何模块
- angular - Angular 不会渲染第二个
- sql - 设计数据库并编写用于分数应用的 SQL 查询
- java - 将 Jasper 报告导出到 Web 应用程序中的 PDF 输出流