在调整大小时,我希望代码运行第一个if语句:"我认为这个太小了"。在第二次调整大小时,我希望它运行第一个备用:"我认为这太大了#34;。 它只运行一个,是因为变量调整只是局部的,并且不会第二次停留?
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>
&#13;
答案 0 :(得分:0)
问题是document.write
。 从不使用document.write
。你可能会想:“哦,我想在文档中写一些东西,所以document.write
似乎很完美”。错了,你被它的名字所迷惑。 Even the specification says it's horrendous
如果您想撰写某些内容,请使用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>
答案 1 :(得分:-1)
如上所述,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>