Javascript 在参数中传递函数,以便在加载时运行
这是在加载时运行的全局函数:Javascript 在参数中传递函数,以便在加载时运行,javascript,jquery,Javascript,Jquery,这是在加载时运行的全局函数: $.fn.loadfns = function(specificfns) { $('#wrapper').hide(); $('#load').fadeIn(400); $(window).load( function() { $('#load').fadeOut(400, function() { $('#wrapper').fadeIn(600, function() {
$.fn.loadfns = function(specificfns) {
$('#wrapper').hide();
$('#load').fadeIn(400);
$(window).load( function() {
$('#load').fadeOut(400, function() {
$('#wrapper').fadeIn(600, function() {
specificfns;
})
})
});
};
问题是,有些页面需要在加载后运行额外的函数(比如将事件插入glDatePicker),所以我尝试将它们作为loadfns的参数传递,比如
$.fn.loadfns("alert('I won't be run');");
但是什么也没发生,它没有被执行。如果我这样做
... rest of function ...
$('#wrapper').fadeIn(600, function() {
alert(specificfns);
})
它会提醒“alert(‘我不会运行’);”(不带括号),它应该作为一个函数来工作。要传递函数,需要传递函数,而不是字符串 如果您只想允许一个额外的函数(当然可以调用其他函数): 这样使用:
$("....").loadfns(function() {
alert("Do something");
});
$("....").loadfns([doSomething, doSomethingElse]);
function doSomething() { /* ... */ }
function doSomethingElse() { /* ... */ }
// They don't have to be named, it's just clearer this way than with inline ones
如果要允许多个额外函数,请传入数组:
$.fn.loadfns = function(extraFunctions) {
$('#wrapper').hide();
$('#load').fadeIn(400);
$(window).load( function() {
$('#load').fadeOut(400, function() {
$('#wrapper').fadeIn(600, function() {
var index;
if (extraFunctions) {
for (index = 0; index < extraFunctions.length; ++index) {
extraFunctions[index]();
}
}
})
})
});
};
如果您想处理异常,可以考虑将“代码> try/catch /<代码>代码块添加到函数中。
通过一个函数,您可以传递函数,而不是字符串。 如果您只想允许一个额外的函数(当然可以调用其他函数): 这样使用:$("....").loadfns(function() {
alert("Do something");
});
$("....").loadfns([doSomething, doSomethingElse]);
function doSomething() { /* ... */ }
function doSomethingElse() { /* ... */ }
// They don't have to be named, it's just clearer this way than with inline ones
如果要允许多个额外函数,请传入数组:
$.fn.loadfns = function(extraFunctions) {
$('#wrapper').hide();
$('#load').fadeIn(400);
$(window).load( function() {
$('#load').fadeOut(400, function() {
$('#wrapper').fadeIn(600, function() {
var index;
if (extraFunctions) {
for (index = 0; index < extraFunctions.length; ++index) {
extraFunctions[index]();
}
}
})
})
});
};
如果您想处理异常,可以考虑将“代码>尝试/捕获-< /COD>”代码块添加到函数中。它起作用了,让我觉得自己很愚蠢!时间一到,我就接受你的回答。@NovAlex:LOL很高兴这有帮助,对不起,这不是为了让你觉得自己愚蠢。:-)非常感谢。它起作用了,让我觉得自己很愚蠢!时间一到,我就接受你的回答。@NovAlex:LOL很高兴这有帮助,对不起,这不是为了让你觉得自己愚蠢。:-)@RaphaëlAlthaus我也读了那篇,对我的情况没有帮助。@RaphaëlAlthaus我也读了那篇,对我的情况没有帮助。