此 Javascript 代码的问题(我认为与执行上下文有关)

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

调整大小时,我希望代码为 运行 第一个 if 语句:"I think this is too small"。在第二次调整大小时,我希望它成为 运行 第一个备用:"I think this is too big"。 它只有 运行 一个,是因为变量调整只是局部的,不会第二次出现吗?

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。你可能会想:"Oh, I want to write something to the document, so document.write seems perfect"。错了,你被它的名字给骗了。 Even the specification says it's horrendous.

当你想写东西时,使用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() 是导致问题的原因。如果你检查他提供的 link 你会明白问题是什么,并且它不明确 causes.So ,避免使用它。但是如果你想使用它,你仍然可以像这样使用它(至少在这种特殊情况下,在这里)。

         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>