gpt4 book ai didi

javascript - 新手方法 : what is a javascript callback function?

转载 作者:可可西里 更新时间:2023-11-01 02:52:35 26 4
gpt4 key购买 nike

只是一个函数在调用它的另一个函数完成后执行吗?

拜托,我(几乎)对编程一无所知,而且我发现很难找到合适的新手答案或解释这意味着什么。

我可以向 stackoverflow 专家请求试用吗?

最佳答案

通常,回调函数会在您调用的另一个函数完成后使用(就像您在问题中所述)。 AJAX 请求就是一个很好的例子:大多数库都有一个功能,允许您在后台向服务器发送请求而无需刷新页面(这使用了 AJAX)。您通常为此 AJAX 函数提供两个回调函数:一个成功函数和一个失败函数。

如果此请求成功,它会调用成功函数,以便您的代码可以执行所需的操作;例如,它可能会刷新部分页面、播放某种动画或提醒用户他们的信息已保存。另一方面,如果失败,回调函数可能会提醒用户他们的数据没有保存,他们应该重试。

回调函数允许库开发人员创建其他人可以使用的非常通用的代码,然后根据他们的需要进行自定义。

下面是一些 jQuery 代码,用于向您展示上面的示例(此代码将不起作用,因为 URL 不存在):

jQuery.ajax(
url: '/mywebsite/somepage.php',

success: function itWorked(returnedData) {
// This is the success function and will be called only if the ajax call
// completes succesfully

alert('Yay it worked! ' + returnedData);
},

error: function itFailed(originalRequest, textStatus, errorThrown) {
// This is the error function and will only be called if the ajax call
// has an error

alert('It failed! ' + textStatus + '. ' + errorThrown);
}
);

编辑:一开始,我说,“一般来说……”。实际上,回调不仅仅用于函数完成时。就像其他答案中所述,它可以在函数内部的任何地方使用:开始、中间、结束。基本思想是代码的开发人员可能不知道您将如何使用他的代码。因此,他使它变得非常通用,让您能够对数据做任何您需要的事情。

一个很好的例子是 jQuery.each方法允许您传入将在“数组”中的每个元素上执行的回调(我说数组是因为它实际上可以迭代许多可能是也可能不是实际数组的东西)。

<a href='someurl.html' class='special_link'>Some URL</a>
<a href='anotherurl.html' class='special_link'>Another URL</a>
<a href='onelasturl.html' class='special_link'>One Last URL</a>

// The following code says: execute the myEachCallbackFunction on every link
// that has a class of 'special_link'
$('a.special_link').each(function myEachCallbackFunction(i) {

// The link variable will contain the object that is currently
// being iterated over. So, the first time through, it will hold
// the 'someurl.html' link, the second time it will hold the
// 'anotherurl.html' link, and the last time it will hold the
// 'onelasturl.html' link
var link = $(this);

// Change the background color of each link to be red
link.css('background-color', 'red');
});

因此,从这个示例中我们可以看出,jQuery 的开发人员实现了 .each 方法,并允许我们对调用它的每个链接做任何我们想做的事情。

关于javascript - 新手方法 : what is a javascript callback function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3523628/

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