Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript变量不起全局作用_Javascript_Variables - Fatal编程技术网

Javascript变量不起全局作用

Javascript变量不起全局作用,javascript,variables,Javascript,Variables,在开始学习PHP之后,我正在学习Javascript 我正在尝试一些基本的东西,但由于某些原因,下面的代码并没有像我预期的那样工作。我对它进行了研究,从我所能看出它应该是有效的 <script type="text/javascript"> showIndex=4; function test(){ showIndex++; alert(showIndex); } </script> showIndex=4; 功能测试(){ showIndex++; 警报(显示索引

在开始学习PHP之后,我正在学习Javascript

我正在尝试一些基本的东西,但由于某些原因,下面的代码并没有像我预期的那样工作。我对它进行了研究,从我所能看出它应该是有效的

<script type="text/javascript">
showIndex=4;

function test(){
showIndex++;
alert(showIndex);
}
</script>

showIndex=4;
功能测试(){
showIndex++;
警报(显示索引);
}
我用图像调用脚本:

<div style="display:inline-block;margin-left:25px;">';
<a href="" onclick="test()" ><img src="_images/next.png" width="100" />    </a>
</div>
”;
它第一次运行的很好,但是当我再次按下按钮时,它仍然有初始变量加1。(这让我觉得它是一个局部变量…) 看起来很直截了当。。。我做错了什么?

删除
并在图像上显示事件,它正在刷新页面。对于
onclick
事件,不需要将其包装在
标记中:

<img src="_images/next.png" onclick="test()" width="100" />

空链接。您可以在其中插入
#

<div style="display:inline-block;margin-left:25px;">
   <a href="#" onclick="test()" >www </a>
</div>


然后一切正常。


尝试设置该链接的
href
,您将看到原因:-)
<div style="display:inline-block;margin-left:25px;">';
     <a href="javascript:test()" ><img src="_images/next.png" width="100" />    </a>
</div>