我是JS新手,下面有一个javascript代码片段:
<script type="text/javascript">
var eatSteak = confirm ("Do you eat steak?");
if (eatSteak) {
document.write("Here's a Steak!");
}else{
document.write("Here's a Tofo!");
}
var happy = prompt ("Are you happy?");
</script>当我在chrome中调试代码时,我看到在确认弹出窗口后给出了yes。它点击代码"document.write("Here's a Steak!");",HTML页面显示"Here's a Steak!",然后代码点击提示弹出窗口。
让我非常困惑的是,当我在chrome中运行它时,“这是牛排!”仅在弹出提示后显示。似乎document.write只有在javascript代码执行后才会生效?或者HTML在javascript之后开始渲染页面?我用谷歌搜索了一下,但找不到类似的问题或答案。
发布于 2017-02-25 06:28:02
它是单线程javascript模型的本质。在做出决定之前,提示、警报等会停止执行,您之前所做的任何DOM操作都会一直等到您超出当前作用域。这在不同的浏览器中可能有所不同,但这取决于DOM操作是如何实现的。
下面的脚本会阻止红色,直到你点击确定(至少在Chrome上,在Firefox上,我惊讶地发现它不起作用:D)
设置为绿色的setColor执行此操作,然后使用setTimeout启动计时器,以便在下一个可能的时间显示警报。这将确保在显示警报之前设置为绿色(在任何浏览器中)
// blocking call until it exits the function (at least, on Chrome, firefox seems to work)
function setColorToRed() {
document.body.style.background = 'red';
alert('Red will come after ok');
}
// none blocking call, works on all browsers
function setColorToGreen() {
document.body.style.background = 'green';
setTimeout(function() {
alert('Green color should have been set');
}, 0);
}<button type="button" onclick="setColorToRed()">Blocking call red</button>
<button type="button" onclick="setColorToGreen()">None blocking call green</button>
https://stackoverflow.com/questions/42449152
复制相似问题