当 Javascript 完成时,如何阻止浏览器“沙漏”(停止颤动)?
-
06-09-2020 - |
题
编写一个小型 HTML 网页,其中包含一些非常简单的 Javascript,我注意到完成后,它一直在旋转(firefox)。我在其他页面上看到过很多次,总是认为这是一个 Javascript 错误或循环问题,但我运行的这个程序肯定已经完成了。
下面是一个执行此操作的小网页的示例。单击按钮并进行处理后,颤动器(感谢 Kooilinc 提供了这个术语)继续运行。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Grade Tester</title>
<script language="javascript" type="text/javascript">
function calculate()
{
var grade = document.getElementById("grade").value.toUpperCase();
switch (grade)
{
case "A":
document.write("Outstanding Achievement");
break;
case "B":
document.write("Above Average");
break;
case "C":
document.write("Average Achievement");
break;
case "D":
document.write("Low Passing Grade");
break;
case "F":
document.write("Failing Grade");
break;
}
}
</script>
</head>
<body>
Grade:<input type="text" id="grade" />
<br /><input type="button" value="Get Result" onclick="calculate()" />
</body>
</html>
我可以通过点击停止(右键单击并停止)来停止它。
脚本完成后,我需要做什么才能让 Javascript 停止处理(或浏览器停止处理)?
注1:这发生在 FF4.01 中,而不是在 IE 或 Chrome 中(对于此代码示例)。
笔记2:我在 switch 语句之后尝试了 window.stop() 函数,它并没有停止 throbber。
根据 Lekensteyn 的回答, switch 语句后的 document.close() 解决了这个问题,但这里有一个根本没有跳动并且不使用 document.close() 的示例。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Lab 9.1</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var phrase = "Every good boy does fine goes on the line."
document.write(phrase.length + "<br />");
for(var i = 0; i < phrase.length; i++)
{
document.write(phrase.charCodeAt(i) + " ");
}
document.write("<br />");
document.write(phrase.toLowerCase() + "<br />");
document.write(phrase.toUpperCase() + "<br />");
</script>
</body>
</html>
解决方案
打电话后 document.write()
, ,你必须打电话 document.close()
如果文档之前未关闭。
基本上,会发生这种情况:
- 页面正在被解析
- 脚本已处理
- 页面已“关闭”(
document.close()
)
如果 document.write()
在第2步中调用,将在第3步中完成。除了第 3 步之外,如果您致电 document.write
, ,您再次打开该页面,但该页面不会在 FF 中自行关闭(不确定其他页面)。你必须通过调用来关闭它 document.close()
.
当我需要打开一个窗口并在FF中快速写入时我发现了这一点。
var win = window.open();
win.document.write("something");
// the next line is required to finish the page
win.document.close();
这同样适用于你的情况:
<script type="text/javascript">
function calculate()
{
var grade = document.getElementById("grade").value.toUpperCase();
switch (grade)
{
case "A":
document.write("Outstanding Achievement");
break;
// removed some cases
case "F":
document.write("Failing Grade");
break;
}
// finish the document
document.close();
}
</script>
不隶属于 StackOverflow