gpt4 book ai didi

javascript - 延迟对象混淆

转载 作者:行者123 更新时间:2023-11-30 18:38:14 24 4
gpt4 key购买 nike

以下代码段按预期工作:

function boxAnimation() {
var dfd = $.Deferred();
$('div').fadeIn('slow', dfd.resolve);
return dfd.promise();
}

$(function () {
boxAnimation().done(
function () { $(this).animate({ 'margin-top': 50 }); },
function () { $(this).animate({ 'margin-left': 150 }); },
function () { $(this).animate({ 'margin-top': 250 }); },
function () { $(this).animate({ 'margin-left': 350 }); }
).fail(function () { alert('failed'); });
});

然而在这一个中,不同的对象既没有被拒绝也没有被解决

请告诉我哪里出错了。

function boxAnimation() {
var dfd = $.Deferred();
var randomNum = Math.floor(Math.random() * 5);
$('div').fadeIn('slow', function () {
if (randomNum == 1) {
dfd.reject;
}
else {
dfd.resolve;
}
});
return dfd.promise();
}

$(function () {
boxAnimation().done(
function () { $(this).animate({ 'margin-top': 50 }); },
function () { $(this).animate({ 'margin-left': 150 }); },
function () { $(this).animate({ 'margin-top': 250 }); },
function () { $(this).animate({ 'margin-left': 350 }); }
).fail(function () { alert('failed'); });
});

我的 body 是:

<div id='box' style='width:200px; height:200px; border:solid 1px #222222; display:none; background:#cccccc'></div>

最佳答案

你应该调用函数;目前您正在访问它们并保持它们不变。通过实际调用 reject/resolve,您实际上是在拒绝/解决问题。

在第一个示例的fadeIn 中,您没有使用() 就传递了它。这是正确的,因为此时您应该保持不变。当动画完成时,jQuery 将在内部调用该函数。

因为在第二个示例中,调用已经在动画完成时执行的函数中,您应该在那个时候调用它们。

if (randomNum == 1) {
dfd.reject(); // '()' calls a function
}
else {
dfd.resolve();
}

其次,在done 处理程序中,thisDeferred 对象。如果你想传递 div,你可以通过在拒绝/解决时传递它来实现:http://jsfiddle.net/PrmQR/1/ .

function boxAnimation() {
var dfd = $.Deferred();
var randomNum = Math.floor(Math.random() * 5);
$('div').fadeIn('slow', function () {
if (randomNum == 1) {
dfd.reject(this); // pass div
}
else {
dfd.resolve(this);
}
});
return dfd.promise();
}

$(function () {
boxAnimation().done(
function (x) { $(x).animate({ 'margin-top': 50 }); }, // x is the div
function (x) { $(x).animate({ 'margin-left': 150 }); },
function (x) { $(x).animate({ 'margin-top': 250 }); },
function (x) { $(x).animate({ 'margin-left': 350 }); }
).fail(function () { alert('failed'); });
});

关于javascript - 延迟对象混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7620743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com