我正在制作一个简单的重定向脚本,它将在 5 秒后将用户重定向到 2.html
。
当我在 Chrome 上测试该脚本时,它可以工作!,但在最新的 Firefox 中,它不会减少秒数并挂起。
我是初学者,已尽我所能,但无法解决这个问题,我在网上查找但无法找到解决方案。我该如何解决这个问题?
我的代码:
index.html:
<html>
<head>
<title>My First Page</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<input type="button" value=" YES " onclick="yes()" />
</body>
</html>
脚本.js:
c=5;
function yes() {
alert("Right");
var ans=0;
while(ans==0){
var x=prompt("Your Name?");
var ans=confirm("Your Name is "+x+" right?");
}
document.write('<h1>Welcome '+x+' </h1><p id="show">You are being redirected in 3 seconds</p>');
function updateShow(){
document.getElementById('show').innerHTML="<h1>You are being redirected in "+c+" seconds</h1>";
c=c-1;
if(c<0){
document.location='2.html';
}
else{
setTimeout(function(){ updateShow(); },1000);
}
}
var iAmTimer= setTimeout(function(){ updateShow(); },1000);
}
2.html:
<html>
<body>
<h1>Welcome</h1>
</body>
</html>
控制台错误消息
- Firefox - 无
- Chrome - 无
输出:
Firefox(永远):
Welcome <name> You are being redirected in 3 seconds
Chrome:
Welcome <name> You are being redirected in 3 seconds Welcome <name> You are being redirected in 2 seconds Welcome <name> You are being redirected in 1 seconds Welcome <name> You are being redirected in 0 seconds
感谢任何帮助。
最佳答案
您应该只使用 document.write()
在加载文档时动态插入内容。
根据MDN's doc :
Writing to a document that has already loaded without calling
document.open()
will automatically perform adocument.open()
call
来自 document.open()
:
If a document exists in the target, this method clears it
所以,使用 document.write()
加载文档后将覆盖(或清除)您的文档。出于这样的原因,using document.write()
is considered a bad practice .
使用
document.body.innerHTML+= '<h1>Welcome ' + x + ' </h1><p id="show">You are being redirected in 3 seconds</p>';
或者事先将内容隐藏在 HTML
中将解决该问题。
另请参阅What are alternatives to document.write?
这在 Chrome 中是如何工作的,对我来说是个谜,恕我直言 - 它不应该。
更新:
来自DOC's :
Also, an automatic
document.open()
call happens whendocument.write()
is called after the page has loaded, but that's not defined in the W3C specification.
所以这不再神秘,因为没有规范,不同的浏览器以不同的方式实现它。又一个避免的理由document.write()
:)
关于javascript - 为什么 document.write() 在 Firefox 和 Chrome 中的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25398005/