jQuery with Callback and Complete
jQuery with Callback and Complete
所以我想在.fadeOut()
完成动画后使用回调函数。我可以使用下面的代码成功地做到这一点,没有问题。工作就像我想要的(HTML和CSS只是一个黑色的正方形div)
function fadeOutThing(speed, callback) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback();
}
});
}
function OtherThing() {
console.log("hello");
}
fadeOutThing(5000, OtherThing);
我真正想要的是这个回调函数有它自己的参数,可以是另一个回调函数,如下所示。问题是,当我这样做时,日志将在动画完成之前显示:
function fadeOutThing(speed, callback) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback();
}
});
}
function OtherThing(stuff) {
console.log("hello" + stuff); //This displays too soon!
}
fadeOutThing(5000, OtherThing(' stuffsss'));
为什么会发生这种情况?我有什么不明白的吗?
这个问题是因为您在加载页面时立即调用OtherThing()
。这意味着你给OtherThing()
函数的结果作为回调参数,而不是给函数的引用。
做你需要的,你可以提供一个匿名函数回调包装你的OtherThing()
调用:
fadeOutThing(5000, function() {
OtherThing(' stuffsss'));
});
按如下方式绑定参数而不是调用函数:
fadeOutThing(5000, OtherThing.bind(this,' stuffsss'));
你在属性中使用/调用函数所以你发送它的返回值而不是函数声明在这种情况下没有返回值所以:
fadeOutThing(5000, OtherThing(' stuffsss'));
=
fadeOutThing(5000, notDeclaredNothing); //undefined variable
发送函数声明和设置参数,你可以这样做,例如第三个参数:
function fadeOutThing(speed, callback,attrs) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback(attrs); //use with attributes
}
});
}
用法:
fadeOutThing(5000, OtherThing,'stuffsss');
或者第二个选项是使用bind - bind创建具有给定this和给定属性的新函数:
fadeOutThing(5000, OtherThing.bind(this,'stuffsss'));
相关文章:
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- Rails 3.2 and Paloma gem
- Backbone, TypeScript, and super
- iframe and JavaScript on different pages
- JSON and jQuery Search
- Kendo UI Complete (Trial) and Eclipse Juno: kendo.web.min.js
- jQuery with Callback and Complete