2017-06-04 54 views
0

为什么JavaScript中的提示对话框在之前编写的代码之前运行? 例如 在这个代码中,我认为首先应该显示“主标题”,然后是for循环,只有在该提示对话之后?JavaScript中的提示对话框在之前编写的代码之前运行

<h1 id="main-heading">Hello World!!!</h1> 
<script> 
    var friends= ["Olya", "Dima", "Dan", "Dennis", "Sasha" ]; 
    for (var r= 0, rmax= friends.length; r < rmax; r++) { 
    $("body").append("<p>" + friends[r] + "</p>"); 
    console.log('friends[r]', friends[r]); 
    }   
    var newHeading= prompt("Enter NEW Heading"); 
    $("#main-heading").text(newHeading); 
</script> 
+0

之前'prompt'的代码运行的,但你不能看到它的效果,因为该提示框停止重画页。 –

+0

另外,[这个问题](https://softwareengineering.stackexchange.com/q/106031/211784)解释了为什么使用'prompt'不是一个好主意。 –

回答

1

身体标记尚未关闭,因此无法呈现/绘制。 您可能希望等待加载内容,方法是将代码添加到回调函数中,该函数在之后运行html已被呈现。使用jQuery,它真的很容易做到使用jQuery ready

$(function(){ 
    //Everything is loaded, let's manipulate the body 
}); 
+0

[-1不够jQuery](http://needsmorejquery.com/) –

相关问题