我之前尝试过,但它不起作用.是代码的错误吗?
<script type ="text/javascript">
function count()
{
var x = 0;
x += 1;
document.getElementById( "counting" ).value = x;
}
</script>
</head>
<body>
<input type ="button" value = "Click" onclick = "count()"/><br><br>
<input id = "counting" type = "text" />
</body>
Run Code Online (Sandbox Code Playgroud)
您需要将该行移动var x = 0;
到函数外部的某个位置count
,以使其位于全局范围内.这意味着该函数对其所做的更改count
将持续存在.
例如
var x = 0;
function count() {
x += 1;
document.getElementById( "counting" ).value = x;
}
Run Code Online (Sandbox Code Playgroud)