在确认之前执行功能 jquery

Do function before confirm jquery

这是我的 jquery 代码

$('.input').keyup(function(event){
    update_text(); // $('div').html('blahblah');
})
.blur(function(event){
    $(this).keyup();
    if(confirm('Are you sure?')){
        // do somthing...
    }
});

我的问题是输入模糊时,确认框应该在执行 update_text();

后显示

但 update_text() 在确认后似乎 运行...

如何让它先执行 update_text(),然后显示确认对话框?

这可能太简单了,但似乎解决了问题。

$('.input').keyup(function(event){
  update_text(); // $('div').html('blahblah');
})
$('.input').blur(function(event){
  update_text();
  if(confirm('Are you sure?')){
    // do somthing...
  }
});

实际上您的方法在 confirm() 之前执行 运行,这里的问题是您的浏览器异步重绘 DOM,即使方法 .html() 本身是同步的。因此,虽然 运行 首先从视觉上看它确实如此。

例如,更简单的版本将具有相同的功能,但可能因浏览器而异:

$("div").html("foo");
confirm('Are you sure?');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

解决此问题的一种方法是 force the DOM to repaint 而不是让浏览器执行此操作。例如:

$("div").html("foo");
$("div").hide().show(function(){
  confirm('Are you sure?'); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

update_text() 发生在 keyup 事件上,该事件在输入模糊之前触发,因此如果设置正确,它实际上会在每次用户输入另一个字符时发生。

$('.input').keyup(function(event){
    update_text(); // $('div').html('blahblah');
})
.blur(function(event){
    $(this).keyup();
    if(confirm('Are you sure?')){
        // do somthing...
    }
});

update_text = function() {
  text = $('.input').val();
  $('#text').text(text);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='input'/>
<div id='text'>