在谷歌浏览器中进行某种缓存?

时间:2017-05-05 06:40:01

标签: javascript google-chrome

我有一个简单的问题,下面的代码显示了一些按钮(“按下”)并询问用户“你多大了?”如果用户回答的数字大于20,则代码写入页面“nice”。 问题是循环,所以代码问了7次这个问题。

问题(我的问题)是:循环结束后出现“好”,为什么?它就像一些缓存。 当命令“document.writeln(”nice“)执行时它为什么不出现?

这种现象就在我从Chrome运行时,它不会发生在EDGE或IE中。我能在CHROME中设置哪种CACHING不会发生?  谢谢

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<script>
 function run() 
 {
    var i = 1;
	var x = 0;
	while (i<8)
	{
	  x = window.prompt(i+ " how old are you  ");
	  if (x>20)
	  {
	     document.writeln("nice" + " " + i + "<br>");
 	  }
	  i = i+1;
	}
 
 }
</script>

</head>
<body>
<input type="button" value="press" onclick="run()">
</body>
</html>

2 个答案:

答案 0 :(得分:0)

如果数字大于20,请添加break;以退出循环。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<script>
 function run() 
 {
    var i = 1;
	var x = 0;
	while (i<8)
	{
	  x = window.prompt(i+ " how old are you  ");
	  if (x>20)
	  {
	     document.writeln("nice" + " " + i + "<br>");
             break;
 	  }
	  i = i+1;
	}
 
 }
</script>

</head>
<body>
<input type="button" value="press" onclick="run()">
</body>
</html>

答案 1 :(得分:0)

我认为这是因为不同的浏览器在何时以及如何允许document.write调用更改DOM时具有不同的行为。

看起来firefox会立即更改文档,并且chrome会在进行更改之前等待当前正在执行的函数完成。

有一个非常普遍的建议是完全避免使用document.write。请参阅https://stackoverflow.com/a/25398255/121660以获得相当不错的解释。

更改要使用的代码段:

document.body.innerHTML+="nice <br/>"代替document.write我也没有真正解决这个问题。奇

使用setTimeout(function(){document.write("nice")},0)对我来说也不起作用。