繁体   English   中英

此Javascript代码存在问题(我认为是执行上下文)

[英]Issue with this Javascript code (I think with the execution context)

在调整大小时,我希望代码运行第一个if语句:“我认为这太小了”。 在第二次调整大小时,我希望它运行第一个备用项:“我认为这太大了”。 它只运行一次,是因为变量调整仅是局部的并且不会第二次停留吗?

 var counter = 0; function message() { if (counter == 0) { document.write("I think this is too small"); counter = counter + 1; } else if (counter == 1) { document.write("I think this is too big"); counter = counter + 1; } else { confirm("Third Time's a charm"); } } window.addEventListener('resize', message, false); 
 <p>Text</p> 

问题是document.write 切勿使用document.write 您可能会想:“哦,我想在文档中写点东西,所以document.write看起来很完美”。 错,您被它的名字迷住了。 甚至规范都说这太可怕了

当您想写东西时,请使用textContentinnerHTML或DOM方法。

 var target = document.querySelector('p'); var counter = 0; function message() { if (counter == 0) { target.textContent = "I think this is too small"; counter = counter + 1; } else if (counter == 1) { target.textContent = "I think this is too big"; counter = counter + 1; } else { target.textContent = "Third Time's a charm"; } } window.addEventListener('resize', message, false); 
 <p>Text</p> 

如上所述,document.write()引起了问题。如果您检查他提供的链接,您将会了解问题的根源和歧义。因此,请避免使用它 。但是如果您仍然想使用它,您仍然可以可以像这样使用它(至少在这种情况下,在这里)。

  var counter = 0; function message() { if (counter == 0) { document.write("I think this is too small"); counter = counter + 1; window.addEventListener('resize', message, false); } else if (counter == 1) { document.write("I think this is too big"); counter = counter + 1; window.addEventListener('resize', message, false); } else { confirm("Third Time's a charm"); window.addEventListener('resize', message, false); } } window.addEventListener('resize', message, false); 
 <p>Text</p> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM