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条)

报告相同问题?

悬赏问题

  • ¥15 github符合条件20分钟秒到账,github空投 提供github账号可兑换💰感兴趣的可以找我交流一下
  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?