javascript中变量作用域的问题
好吧,我确实很困惑,为什么这不在文本区域返回 6。它不返回任何内容。 我认为这与 js 范围有关,但我无法弄清楚。
<body>
<script language="Javascript">
var broj = 5;
function Inci(){
var broj++;
document.frmMain.VrsteHolder.value = broj;
}
</script>
<form name="frmMain" method="get" action="script.php">
<textarea name="VrsteHolder" rows="4"> </textarea>
<input type="button" value="Dodaj porudzbinu" name="buttonDodaj" onClick="Inci();"/>
</form>
</body>
Ok I am definitely puzzled, why this is not returning 6 in textarea. It doesn't return anything.
I figured that it has something to do with js scopes, but i cant figure it out.
<body>
<script language="Javascript">
var broj = 5;
function Inci(){
var broj++;
document.frmMain.VrsteHolder.value = broj;
}
</script>
<form name="frmMain" method="get" action="script.php">
<textarea name="VrsteHolder" rows="4"> </textarea>
<input type="button" value="Dodaj porudzbinu" name="buttonDodaj" onClick="Inci();"/>
</form>
</body>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
删除
Inci
函数内的var
关键字。var
重新声明当前范围内的变量,因此每次调用Inci
都会重新声明broj
。这将是正确的方法:
Get rid of the
var
keyword inside of theInci
function.var
redeclares variables in the current scope, so it will redeclarebroj
every invocation ofInci
.This would be the correct way:
因为
var
关键字定义了变量。从函数中删除var
:because the
var
keyword defines the variable. Removevar
from your function:问题是
var
作为其他答案的详细信息,重新声明您的变量,或者尝试,并且实际上由于组合而引发语法错误。顺便说一句,虽然我看到的较少:不要忘记您可以通过使用 ++ 来增加并立即获得结果(增量运算符) 在变量之前,例如:
您可以在此处测试该版本。
The problem is
var
as the other answers detail, redeclaring your variable, or attempting to rather, and actually throwing a syntax error because of the combination.As an aside though that I'm seeing less: don't forget you can increment and get the result immediately by having the ++ (increment operator) before the variable, for example:
You can test that version out here.