为什么我不能在函数外部输出,在这种情况下,我正在创建一个简单的计数器,我很困惑为什么它在内部而不是在外部工作?
Why can't i output outside a function, in this scenario where i'm creating a simple counter i'm confused as to why it's working inside and not out?
这里为什么不能在函数外输出,为什么要在函数内?
counter = 0;
function countJar() {
counter += 1
document.getElementById('demo').innerHTML = counter;
}
// why can't it be here?
因为如果它是您在问题中显示的位置,则该值为 0
。代码 运行 在页面加载时立即执行,它不会等待调用 countJar
。它现在所在的位置,在调用 countJar
之前不会 运行。
如果 你的意思是当你试图把它放在那里时你甚至看不到 0
,那是因为 id="demo"
元素没有'还不存在。如果那是你的意思,this question's answers 适用。
这里为什么不能在函数外输出,为什么要在函数内?
counter = 0;
function countJar() {
counter += 1
document.getElementById('demo').innerHTML = counter;
}
// why can't it be here?
因为如果它是您在问题中显示的位置,则该值为 0
。代码 运行 在页面加载时立即执行,它不会等待调用 countJar
。它现在所在的位置,在调用 countJar
之前不会 运行。
如果 你的意思是当你试图把它放在那里时你甚至看不到 0
,那是因为 id="demo"
元素没有'还不存在。如果那是你的意思,this question's answers 适用。