dtz8044 2011-02-04 21:33
浏览 38
已采纳

Javascript - 在结束函数之前等待单击

I have made what is essentially a lightbox whereby if a change requires the user to confirm their password, this lightbox pops up and the user enters there password etc.

I am triggering the function like this:

if(verifyPassword())
{
    //apply change
}

The verify function is:

function verifyPassword() {
$('#confirmpasswordoverlay').fadeIn(300);

$('#submit').click(function() {
    $.post('', { password: $('input[name=password]').val() }, 
            function(check) {
                if(check.error)
                {
                    if(check.password)
                    {
                        //show password error
                        return false;
                    }
                    else
                    {
                        //show error
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }, 'json');
});

}

Basically I am needing the function to wait until #submit is clicked to return either true or false.

Thanks in advance

  • 写回答

3条回答 默认 最新

  • dongqi0644 2011-02-04 21:40
    关注

    Since jQuery 1.5.0, you can do apply some magic with Deferred objects:

    $.when( verifyPassword() ).done(function() {
        // do something
    });
    

    You would need to re-write verifyPassword() a little:

    function verifyPassword() {
        var Notify = $.Deferred();
        $('#confirmpasswordoverlay').fadeIn(300);
    
        $('#submit').click(function() {
            $.post('', { password: $('input[name=password]').val() }, 
                    function(check) {
                        if(check.error) {
                            if(check.password) {
                                //show password error
                                Notify.resolve();
                            }
                            else {
                                //show error
                                Notify.reject();
                            }
                        }
                        else {
                            return true;
                        }
                    }, 'json');
            });
    
        return Notify.promise();
    }
    

    This might not be the most elegant way of achieving your goal here, I'm just saying you could do it in a way like this :-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?