Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The question is actually quite simple. How do I make the div's content change before the alert shows up?

JSFiddle:

https://jsfiddle.net/n2n5drL2/1/

HTML:

<div id="test">
Some Text
</div>
<button id="change">
change
</button>

JavaScript:

$('#change').click(function(){
  $('#test').text('new content');
  alert('how to make this alert shows after the div changes its content?')
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
119 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to defer execution of the blocking alert so the browser can re-render the changed DOM. You can do this with setTimeout and a 0ms timeout:

$('#change').click(function(){
  $('#test').text('new content');
  setTimeout(function() {
    alert('how to make this alert shows after the div changes its content?')
  },0);
})

It is worth noting, however, that the specification for alert says to only

Optionally, pause while waiting for the user to acknowledge the message.

So while I've personally never seen a user-agent treat it as non-blocking, the specification does allow for it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...