jquery - jQuery 中的空花括号

标签 jquery

在片段中, $({}).queue(function(next){}) $({}) 代表什么?人们为什么使用这种形式?

我从 this answer here on SO 获取了代码.

最佳答案

更新答案

您的comment below您指的是 this answer 中的代码显着改变事情。

该答案中的代码:

$(document)
  .queue(callMe1)
  .queue(callMe2);

...然后有一条评论建议使用 {} 而不是 document:

$({})
  .queue(callMe1)
  .queue(callMe2);

您可以这样做来建立一个调用链,其中链中的后续调用只有在前面的调用完成后才会发生。他们所做的事情可以是同步的,也可以是异步的。这是一种早期的 promise 形式。

举个例子:假设我想做三件事,一件接着一件,每一件事情可能会也可能不会异步执行某些操作,例如动画。我们可以这样做:

$({}).queue(theFirstThing)
     .queue(theSecondThing)
     .queue(theThirdThing);

...直到前面的函数表示它们已完成后,后面的函数才会被调用。

示例:

$({}).queue(theFirstThing)
     .queue(theSecondThing)
     .queue(theThirdThing);

function theFirstThing(next) {
  // What I do is asynchronous: Fade out the a1 element,
  // then call the next function in the chain if any
  $("#a1").fadeOut("slow", next);
}
function theSecondThing(next) {
  // What I do is synchronous
  $("<p>Hi there</p>").appendTo(document.body);
  
  // Chain to next if any
  next();
}
function theThirdThing(next) {
  // What I do is asynchronous: Fade out the a2 element,
  // then call the next function in the chain if any
  $("#a2").fadeOut("slow", next);
}
<div id="a1">a1</div>
<div id="a2">a2</div>
<div id="a3">a3</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<小时/>

原始答案:

The documentation告诉我们:

jQuery( object )

object
Type: PlainObject
A plain object to wrap in a jQuery object.

例如,它将 jQuery 实例包装在普通对象周围。我们习惯于 jQuery 实例包裹一个或多个 DOM 元素,但它们也可以包裹其他东西。

然后他们正在做queue在生成的 jQuery 对象上:

.queue( [queueName ], callback )

queueName
Type: String
A string containing the name of the queue. Defaults to fx, the standard effects queue.

callback
Type: Function( Function next() )
The new function to add to the queue, with a function to call that will dequeue the next item.

这告诉我们它在做什么:将 jQuery 对象包装在一个普通对象周围,然后调用 queue 将某些内容放入该 jQuery 对象的默认动画队列中,即使其中没​​有元素它的动画。

Why do people use this form?

我从来没见过这样用过。我想不出任何理由使用它,如您的问题所示,它只是在 queue 调用期间立即调用该函数,正如我们在这里看到的:

$({}).queue(function(next){
  snippet.log("Function called");
  next();
});
snippet.log("queue call complete");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

关于jquery - jQuery 中的空花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29263068/

相关文章:

jquery - 设置为使用 nicEdit 的文本区域中的内容不会更新以反射(reflect)用户更改

javascript - 谷歌地图在 Bootstrap 模态中的位置总是偏离 map 大小宽度和高度

javascript - 如果数组中的位置超过 5 个,则显示不同的值

javascript - 如果有人知道如何用循环和 .map 解决这个问题

javascript - 无限滚动更改ID问题

javascript - 使用 css 类切换背景颜色

jquery - 通过使用 jQuery 解析 sessionID 从 WCF 服务访问 session 变量

php - Ajax 发布带有数字但不带有字母的字符串

jquery - 用 jquery 去除所有 html 标签?

jquery - 在兼容模式下使用 jQuery 检测 IE 版本