javascript中变量作用域的问题

发布于 2024-10-16 15:48:34 字数 542 浏览 13 评论 0原文

好吧,我确实很困惑,为什么这不在文本区域返回 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甜心 2024-10-23 15:48:34

删除 Inci 函数内的 var 关键字。

var 重新声明当前范围内的变量,因此每次调用Inci都会重新声明broj

这将是正确的方法:

var broj = 5;  

function Inci(){
   document.frmMain.VrsteHolder.value = ++broj;
}

Get rid of the var keyword inside of the Inci function.

var redeclares variables in the current scope, so it will redeclare broj every invocation of Inci.

This would be the correct way:

var broj = 5;  

function Inci(){
   document.frmMain.VrsteHolder.value = ++broj;
}
夜深人未静 2024-10-23 15:48:34

因为 var 关键字定义了变量。从函数中删除 var

function Inci(){
    broj++;
    document.frmMain.VrsteHolder.value = broj;
    }

because the var keyword defines the variable. Remove var from your function:

function Inci(){
    broj++;
    document.frmMain.VrsteHolder.value = broj;
    }
抱猫软卧 2024-10-23 15:48:34

问题是 var 作为其他答案的详细信息,重新声明您的变量,或者尝试,并且实际上由于组合而引发语法错误。

顺便说一句,虽然我看到的较少:不要忘记您可以通过使用 ++ 来增加并立即获得结果(增量运算符) 变量之前,例如:

function Inci(){
  document.frmMain.VrsteHolder.value = ++broj;
}

您可以在此处测试该版本

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:

function Inci(){
  document.frmMain.VrsteHolder.value = ++broj;
}

You can test that version out here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文