功能调用另一个函数,但不等待返回值



因此,我具有一个基本上调用另一个函数的JavaScript函数。此其他功能返回真或错,然后我有一个if语句,但是该函数不等待返回该值,它只能通过代码拨入。这个解决方案是什么?

所以我的第一个功能具有:

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

and呼叫:

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
    }
});

解决方案是使用回调。您不能在浏览器中具有可行的阻止功能。

让您的show_confirstration函数采用一个函数参数,该函数参数带有返回值。

function show_confirmation(message, height, callback) {
        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");
            callback(true);
        });
        $('#noButton').click(function (e) {
            e.preventDefault();
            $('.confirmBox').hide("slow");  
            callback(false);     
        });
    }
function someAnotherFunction(value){
    if(value){
         //yesButton
    }else{
         //noButton
    }
}

用法:

show_confirmation("message", 0, someAnotherFunction);

最新更新