.promise()

.promise( [ type ], [ target ] ) 官网原E文: Promise

描述: 返回一个 Promise 对象用来观察当某种类型的所有行动绑定到集合,排队与否还是已经完成。

  • version added: 1.6.promise( [ type ], [ target ] )

    type 需要待观察队列类型。

    target附有promise 方法的Object

.promise()方法返回一个动态生成的Promise对象用来观察当某种类型的所有行动绑定到集合,排队与否还是已经完成。

默认情况下, type"fx" ,这意味着当选定的元素已完成所有动画是返回的Promise是解决的。

解决上下文和唯一的参数是哪个集合到.promise()被调用。

如果target是提供,.promise()将附加到它的方法,然后返回这个对象,而不是创建一个新的。这对在已经存在的对象上附加Promise的行为非常有用。

Examples:

Example: 一个集合上使用promise,而没有动画解决的promise:


var div = $( "<div />" );

div.promise().done(function( arg1 ) {
  // will fire right away and alert "true"
  alert( this === div && arg1 === div );
});

Example: Resolve the returned Promise when all animations have ended (including those initiated in the animation callback or added later on):

<!DOCTYPE html>
<html>
<head>
  <style>
div {
  height: 50px; width: 50px;
  float: left; margin-right: 10px;
  display: none; background-color: #090;
}
</style>
  <script src="http://code.jquery.com/jquery-git.js"></script>
</head>
<body>
  
<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>


<script>
$("button").bind( "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>

Demo:

Example: Resolve the returned Promise using a $.when() statement (the .promise() method makes it possible to do this with jQuery collections):

<!DOCTYPE html>
<html>
<head>
  <style>
div {
  height: 50px; width: 50px;
  float: left; margin-right: 10px;
  display: none; background-color: #090;
}
</style>
  <script src="http://code.jquery.com/jquery-git.js"></script>
</head>
<body>
  
<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>


<script>
var effect = function() {
  return $("div").fadeIn(800).delay(1200).fadeOut();
};

$("button").bind( "click", function() {
  $("p").append( " Started... ");

  $.when( effect() ).done(function() {
    $("p").append(" Finished! ");
  });
});

</script>

</body>
</html>

Demo:

jQuery 1.6 API 中文版Clove整理、修订