jQuery:重写匿名回调到命名函数 [英] jQuery: Rewriting Anonymous Callback to a Named Function

查看:186
本文介绍了jQuery:重写匿名回调到命名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做:

  $('h1')。slideUp('slow',function ('div:first')。fadeOut();}); 

h1将向上滑动,然后第一个div将淡出。


然而,如果我这样做:

  function last(){$('div:first' )。消退(); } 

$('h1')。slideUp('slow',last());

h1将向上滑动,div将同时淡出!



如何使我的第二个示例与第一个示例一样工作,其中fadeOut()被称为AFLE slideUp()?

解决方案

您不需要使用函数返回值(通过调用函数),但是函数体:

  $('h1')。slideUp('slow',last); 






您所做的是相同的: / p>

  var returned = last(); //调用最后一次返回未定义
//所返回的值未定义
$('h1')slideUp('slow',returned); //发送未定义为回调

所以你只是执行 last 函数内联,然后将返回值(它是 undefined ,因为它不返回任何内容)作为参数传递给 slideUp






希望此示例可以帮助您理解:



 


If I do this:

$('h1').slideUp('slow', function() { $('div:first').fadeOut(); });

h1 will slide up, then the first div will fade out.

However, if I do this:

function last() { $('div:first').fadeOut(); }

$('h1').slideUp('slow', last());

h1 will slide up and div will fade out at the same time!

How can I make my second example work the same as the first one, where fadeOut() is called AFTER slideUp()?

解决方案

You don't need to use the function return value (which you get by calling the function), but the function body:

$('h1').slideUp('slow', last);


What you did is the same as this:

var returned = last();             // call to last returns undefined
                                   // so returned has the value undefined
$('h1').slideUp('slow', returned); // simply sending undefined as a callback

So you were just executing the last function inline, and then passing the return value (which is undefined since it returns nothing) as a parameter to the slideUp's callback function.


Hope this example will help you understand:

function outer() {
  function inner() {};
  return inner;
}

alert(outer);    // returns the outer function body
alert(outer());  // returns the outer function's return value, which is the inner function

这篇关于jQuery:重写匿名回调到命名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆