gpt4 book ai didi

javascript - 如何在 Javascript 中使用 ,function (){ 实现回调函数

转载 作者:行者123 更新时间:2023-12-03 05:02:44 24 4
gpt4 key购买 nike

我知道如何执行核心回调和函数,但我想要这个用例:

   loadCSSFunction('/stylesheets/swiper.css',function (e){

Execute code
//Do some jquery call to a plugin for example

});

我如何构造 loadCSSFunction 才能形成这些函数,因此一旦发生操作(将 CSS 注入(inject) head (我对此很满意)),我就可以执行依赖于 CSS 注入(inject)的东西。

更新:请注意,此 CSS 元素不相关,它只是示例的一部分,与问题无关。如果我确实想异步注入(inject)等,我会这样做。

函数调用:

   doSomethingWithFile('/folder/file.file',function (e){

Execute code

});

功能:

doSomethingWithFile: function(file){
var mything = 'thing'+file;

}

最佳答案

只需使用回调参数定义您的函数即可。

例如。

function loadCSSFunction(url, callback) {
//do you CSS loading.
//we have now loaded lets call the callback
var e = 'something to pass to callback';
callback(e);
}

你对文件所做的事情与你的 CSSloader 没有太大不同。

doSomethingWithFile: function(file, callback){
var mything = 'thing'+file;
//do what you want to do with file,
//again it doesn't matter if it's async / sync.
//just call the callback when done..
//eg below, readFileContents might be an async function
readFileContents(file, function (err, data) {
//normally async callbacks usually pass an err param
//you should normally check for this too.
if (err) callback(err); //if we have error pass it along.
else callback(null, data); //here were sending our result back
});
}

现在我们可以使用 doSomethingWithFile..

doSomethingWithFile('thefile.txt', function (err, data) {
if (err) console.error(err);
else console.log(data);
});

关于javascript - 如何在 Javascript 中使用 ,function (){ 实现回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42148461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com