0

在调整大小时,我希望代码运行第一个 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>

4

2 回答 2

0

问题是document.write永远不要使用document.write. 你可能会想:“哦,我想给文档写点东西,document.write看起来很完美”。错了,你被它的名字给骗了。甚至规范都说这太可怕了

当你想写东西时,使用textContent,innerHTML或 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>

于 2016-06-04T19:06:00.177 回答
-1

如上所述,document.write() 导致了问题。如果您检查他提供的链接,您将了解问题是什么以及它导致了歧义。所以,避免使用它。但如果你想使用它,你可以像这样使用它(至少在这种特殊情况下,here)。

         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>

于 2016-06-04T19:38:34.360 回答