【问题标题】:jQuery fadeOut callback function - why would local function won't work while global function will?jQuery fadeOut 回调函数 - 为什么局部函数不起作用而全局函数会起作用?
【发布时间】:2015-09-19 16:39:50
【问题描述】:

我得到了一个简单的twitter bootstrap 消息框,我在上面写了一些小 jQuery 效果。

首先我淡出板子,一旦它完成淡出,我就在写我想要的,然后他们再次淡入。

我有 2 个版本:

第一个,使用本地定义函数

function postMessage(message, context) {
    if(typeof context === 'undefined')
        context = "info";

    var newClass = "alert alert-" + context;
    var messageBoard = $("#messageBoard");
    // Fade out
    messageBoard.fadeOut('slow', postFadeOut);

    var postFadeOut = function() {
        alert("XX");
//      $(this).attr('class', newClass);
//      $(this).html(message);
//      // Fade in again
//      $(this).fadeIn('slow');
    }
}

它不会触发alert("XX"),但是:

function postMessage(message, context) {
    if(typeof context === 'undefined')
        context = "info";

    var newClass = "alert alert-" + context;
    var messageBoard = $("#messageBoard");
    // Fade out
    messageBoard.fadeOut('slow', postFadeOut);
}

function postFadeOut() {
    alert("XX");
//  $(this).attr('class', newClass);
//  $(this).html(message);
//  // Fade in again
//  $(this).fadeIn('slow');
}

触发。为什么?

【问题讨论】:

  • 尝试在调用.fadeOut() 之前声明var postFadeOut 吗?当= 运算符在if 语句中时,if 语句应该有括号{} 吗?可以在问题中包含html 吗?

标签: javascript jquery function callback scope


【解决方案1】:

这是variable hoisting 效果。

在 JavaScript 中,变量被提升。这意味着在它们被声明的范围内,它们可以在任何代码行中使用,即使在该行之后声明。但是,它们的值或初始化是按照编写代码的顺序发生的。例如:

alert(a);
var a = 'Some value';
alert(a);

如您所见,a 在第一个警报中可用(不抛出异常),但未初始化。

上面的代码在所有用途上都等同于:

var a;
alert(a);
a = 'Some value';
alert(a);

在您的第一个示例中,postFadeOut 变量像这样被提升,但在 .fadeOut 调用中它未初始化,其值为 undefined

第二个版本的工作原理是函数在它们声明的范围内可用,无论代码顺序如何。这是因为引擎首先解析整个代码,“记住”该通道中的函数,然后才从第一行开始执行。

【讨论】:

  • 很好的答案!谢谢!
【解决方案2】:

尝试在调用messageBoard.fadeOut('slow', postFadeOut)之前声明postFadeOut变量

function postMessage(message, context) {
    if(typeof context === 'undefined') {
        context = "info";
    };
    var newClass = "alert alert-" + context;
    var messageBoard = $("#messageBoard");
    var postFadeOut = function() {
        $(this).attr('class', newClass);
        $(this).html(message);
        // Fade in again
        $(this).fadeIn('slow');
    }
    // Fade out
    messageBoard.fadeOut('slow', postFadeOut);
}

postMessage("message")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="messageBoard">message board</div>

【讨论】:

    猜你喜欢
    • 2012-05-12
    • 2015-10-04
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多