gpt4 book ai didi

javascript - 函数调用另一个函数但不等待返回值?

转载 作者:行者123 更新时间:2023-12-01 02:28:42 25 4
gpt4 key购买 nike

所以我有一个 javascript 函数,它基本上调用另一个函数。这个其他函数返回 true 或 false,然后我有一个 if 语句,但是该函数不会等待返回值,它只是继续浏览代码。有什么解决方案吗?

所以我的第一个函数是:

confirmmation = show_confirmation("<some text>", "245px");
if (confirmmation) {
return true;
}
else {
return false;
}

这调用了:

function show_confirmation(message, height) {
var contentPosition = $('.content').position();
var contentHeight = $('.content').height();
var bottomPosition = contentPosition.top + contentHeight;
$('.confirmBox').css("top", (bottomPosition - ($('.confirmBox').outerHeight()+100)) + "px");
$('.confirmBox').css("left", (($('.content').width() - $('.confirmBox').outerWidth()) / 2) + $('.content').scrollLeft() + "px");
$('.confirmBox').css("height", height);
$('.confirmBox .confirmationMessage').html(message)
$('.confirmBox').css("display", "block");

$('#yesButton').click(function (e) {
e.preventDefault();
$('.confirmBox').hide("slow");
return true;
});
$('#noButton').click(function (e) {
e.preventDefault();
$('.confirmBox').hide("slow");
return false;
});
}

最佳答案

您应该使用回调:

function show_confirmation(message, height, callback) {
// ...

$('#yesButton').click(function (e) {
e.preventDefault();
$('.confirmBox').hide("slow");
callback(true);
});
$('#noButton').click(function (e) {
e.preventDefault();
$('.confirmBox').hide("slow");
callback(false);
});
}

show_confirmation("<some text>", "245px", function(confirmation) {
if (confirmation) {
// yes button clicked
}
else {
// no button clicked
}
});

关于javascript - 函数调用另一个函数但不等待返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30059492/

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