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

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

javascript - How to make the HTML renders before the alert is triggered?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...