为了账号安全,请及时绑定邮箱和手机立即绑定

如何在jquery click函数中等待确认

如何在jquery click函数中等待确认

智慧大石 2023-07-06 09:53:42
您好,我有一个要求,我需要等待确认才能完成。注意:我无法在点击(大块)内触摸我的前辈的以下代码或将它们包裹起来.then(function(){..});这是我尝试过但给出错误的:async function showConfirmationAndWait(){    $.alertable.confirm('You sure?').then(function() {      return new Promise(function(res,rej){           res({confirmed:true});      });    }, function() {       return new Promise(function(res,rej){           res({confirmed:false});      });      });}  $('#await').on('click',function(){    var promiseObj =  await showConfirmationAndWait(); //throwing error        //...... big code with its own function call that i don't want to touch });问题: 我想等到确认完成而不用包装老年人的整个代码.then(function(){..});这是我尝试过的:async function showConfirmationAndWait(){    $.alertable.confirm('You sure?').then(function() {      return new Promise(function(res,rej){           res({confirmed:true});      });    }, function() {       return new Promise(function(res,rej){           res({confirmed:false});      });      });}  $(function(){    $('#await').on('click',function(){        var promiseObj =  await showConfirmationAndWait(); //commented due to error         console.log('after await promiseObj',promiseObj);             //...... big code with its own function call that i don't want to touch    });}); <link href="https://cdn.rawgit.com/claviska/jquery-alertable/master/jquery.alertable.css" rel="stylesheet"/><script src="https://code.jquery.com/jquery-2.2.4.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.ui.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js"></script><script src="https://rawgit.com/claviska/jquery-alertable/master/jquery.alertable.min.js"></script><button id="await">Show confirmation wait and proceed next line</button>
查看完整描述

1 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

您需要重写showConfirmationAndWait 以实际等待确认并返回结果。


还将您的整个处理程序标记为async.


async function showConfirmationAndWait() {

  try {

    await $.alertable.confirm('You sure?');

    return true

  } catch {

    return false

  }

}


$(function() {

  $('#await').on('click', async function() {

    var promiseObj = await showConfirmationAndWait();

    console.log('after await promiseObj', promiseObj);


    //...... big code with its own function call that i don't want to touch

    console.log('Some scary logic goes here. It should be printed after confirmation.');


  });

});

<link href="https://cdn.rawgit.com/claviska/jquery-alertable/master/jquery.alertable.css" rel="stylesheet" />

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<script src="https://rawgit.com/claviska/jquery-alertable/master/jquery.alertable.min.js"></script>



<button id="await">Show confirmation wait and proceed next line</button>


查看完整回答
反对 回复 2023-07-06
  • 1 回答
  • 0 关注
  • 69 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信