我有一个简单的twitter bootstrap消息框架,我正在写,带有一些小的jQuery效果。
首先,我淡出了董事会,一旦它完成淡出,我正在写我想要的,他们再次淡出它。
我有两个版本:
首先,使用本地定义的函数
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');
}将触发。为什么?
发布于 2015-09-19 17:29:00
这是一个https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting效应。
在JavaScript中,变量被提升。这意味着在声明的范围内,它们在任何代码行中都是可用的,即使在该行之后声明也是如此。但是,它们的值或初始化是按照代码编写的顺序进行的。例如:
alert(a);
var a = 'Some value';
alert(a);
如您所见,a在第一个警报中是可用的(没有抛出异常),但它没有初始化。
上述代码在所有目的上都与以下内容相同:
var a;
alert(a);
a = 'Some value';
alert(a);在您的第一个示例中,postFadeOut变量是这样挂起的,但是在.fadeOut调用中它是未初始化的,它的值是undefined。
第二个版本可以工作,因为函数在声明的范围内是可用的,而不管代码的顺序如何。这是因为引擎首先解析整个代码,“记住”传递中的函数,然后才开始从第一行开始执行。
发布于 2015-09-19 16:50:58
尝试在调用postFadeOut之前声明messageBoard.fadeOut('slow', 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>
https://stackoverflow.com/questions/32670671
复制相似问题