簡體   English   中英

在確認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()之前運行,這里的問題是,即使方法.html()本身是同步的,您的瀏覽器也會異步重繪DOM。 因此,雖然它似乎沒有在視覺上首先運行,但確實是。

例如,一個更簡單的版本將具有相同的功能,具體取決於瀏覽器:

 $("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> 

解決此問題的一種方法是強制DOM重新繪制,而不是讓瀏覽器執行。 例如:

 $("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'> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM