【问题标题】:Do function before confirm jquery在确认jquery之前执行功能
【发布时间】:2017-07-28 03:26:14
【问题描述】:

这是我的 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(),然后显示确认对话框?

【问题讨论】:

  • update_text()confirm() 之后运行,还是update_text() 对页面所做的任何更改直到confirm() 之后才重新绘制?
  • 似乎 update_textconfirm 之前运行。但是.html().val()confirm 之后重绘。 =D

标签: javascript jquery dialog confirm


【解决方案1】:

实际上您的方法确实在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>

【讨论】:

  • "您的浏览器异步更新 DOM" - 它同步更新 DOM,但异步重绘任何结果。 (只是为了今天的挑剔奖。)无论如何,你没有提出解决方案 - 也许使用setTimeout()
  • @nnnnnn 是的,抱歉,我的意思是重绘 DOM。
  • @SpencerWieczorek 这就是我所面临的。感谢您的解释 :)
  • @nnnnnn 我正在使用 setTimeout,它运行良好。谢谢你的建议。 =D
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    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'>

    【讨论】:

    • 这正是我所期望的!可悲的是,它仍然不适用于我的代码。 :|谢谢你的帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多