Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...