Javascript 为什么警报功能先于我的功能

Javascript 为什么警报功能先于我的功能,javascript,jquery,Javascript,Jquery,这是我的代码: function ivideos() { $('#n1').html('hello'); $('#n2').html('hello'); $('#n3').html('hello'); $('#n4').html('hello'); $('#n5').html('hello'); } ivideos(); alert("alert called"); 我不知道为什么在我的函数完成之前调用警报。请帮帮我。您的“alert”函数在“

这是我的代码:

function ivideos() {
     $('#n1').html('hello');
     $('#n2').html('hello');
     $('#n3').html('hello');
     $('#n4').html('hello');
     $('#n5').html('hello');
}
ivideos();
alert("alert called");
我不知道为什么在我的函数完成之前调用警报。请帮帮我。

您的
“alert”
函数在
“function ivideos”
之后被调用,但由于浏览器的原因,第一个警报弹出窗口在呈现html之后可见

查看演示


首先调用
警报(1)
,然后再调用
警报(“调用警报”)。
首先调用函数。只是你看不见而已。 在函数中添加一个警报并查看结果

这是你的电话号码


一切都井然有序。当您将
警报
更改为
控制台.log
时,可以看到首先调用了
ivideos()

function ivideos() {
    console.log("ivideos begin");
    $('#n1').html('hello');
    $('#n2').html('hello');
    $('#n3').html('hello');
    $('#n4').html('hello');
    $('#n5').html('hello');
    console.log("ivideos end");
}
ivideos();
console.log("alert called");

请参见修改的

在函数完成之前不会调用警报

您正在更新函数中的元素,并且这些元素更改得很好。只是元素和屏幕上显示的内容不一样

当代码运行时,浏览器中不会发生其他任何事情;没有其他代码运行,也没有处理任何事件。完成所有代码后,浏览器将继续处理事件,包括根据代码运行时发生的更改更新屏幕。

调用
alert()
直到调用
ivideos()
完成后,才会调用
alert(),但是您看不到调用
ivideos()
的结果,因为浏览器尚未重新绘制元素

显示的代码在单个事件中执行。浏览器可以选择等待,直到完成该事件的执行,直到重新绘制视口

您可以使用
setTimeout()
函数将调用
alert()
推送到后续事件。这样,浏览器将在调用
alert()
之前重新绘制元素


请注意,
alert()
confirm()
prompt()
是唯一的,它们暂停当前事件的执行。

“我不知道为什么在我的函数完成之前调用此警报。”事实并非如此。但可能只有在警报解除后屏幕才会更新。警报发生在函数完成后。你可以分辨出来,因为所有的hello文本都是可见的,而不是。只是浏览器在调用警报之前还没有机会呈现新的HTML。@TravisJ在Chrome中不是这样的……我想这是你的错觉。你需要点击run来获得正确的顺序,你可以转到url,它看起来是这样的。在解释Javascript如何工作时使用“thread”是最令人困惑的。并没有任何不同的线程,只有一个主线程可以完成所有任务。@Guffa-Point。我对“线程”一词的使用有点粗心。我已经编辑了我的答案,改为使用“事件”一词。
 function ivideos() {
     $('#n1').html('hello');
     $('#n2').html('hello');
     $('#n3').html('hello');
     $('#n4').html('hello');
     $('#n5').html('hello');
     alert('hello');
 }
 ivideos();
  alert("alert called");
function ivideos() {
    console.log("ivideos begin");
    $('#n1').html('hello');
    $('#n2').html('hello');
    $('#n3').html('hello');
    $('#n4').html('hello');
    $('#n5').html('hello');
    console.log("ivideos end");
}
ivideos();
console.log("alert called");
setTimeout(function() {
    alert("alert called");
}, 0);