首页 > 解决方案 > 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( ... );

但我看不到如何将这个构造融入我的场景?

标签: javascriptjquery

解决方案


您可以使用 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/ ,请阅读这些链接

希望对你有帮助!!!


推荐阅读