gpt4 book ai didi

jQuery 从 .each() 中的函数返回未定义的字符串

转载 作者:行者123 更新时间:2023-12-01 06:55:47 26 4
gpt4 key购买 nike

我试图从名为“tjekdet”的函数返回一个字符串,但它除了未定义之外不会返回任何内容。我只需要它返回字符串,这样我就可以将结果附加到 $(this)。

我这样做的原因是因为对 test2.php 的请求需要大约 40 秒,所以我宁愿一一做。但没关系。

这与同步调用有关吗?或者我只是完全错过了一些真正基本的东西?

    function tjekdet(name) {
$.get("test2.php", { test: name },
function(data){
// alert(data); returns correctly in the alert
return data;
});
}

jQuery(function($) {
$('.button').live("click",function() {
$(".navn-list").each(function() {
var navn = $(this).text();
var tester = tjekdet(navn);
alert(tester); // returns undefined
});
});

最佳答案

Does this have something to do with synchronous calls?

是的。嗯,实际上它与异步调用有关。在 AJAX get 返回任何内容之前,您的 tjekdet 函数将返回 undefined

将警报放入成功回调中:

$.get("test2.php", { test: name }, function(data) {
alert(data);
//Do whatever you need to do here, not in the other function
});

您可以使用jQuery.ajax而不是 jQuery.get 并将 async 选项设置为 false,但这很少是一个好主意,并且往往会完全锁定浏览器,直到数据已返回。

关于jQuery 从 .each() 中的函数返回未定义的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9229685/

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