显示关闭HTML页面
问题描述:
我正在尝试在JS中练习范围闭包,我很坚持在Html页上实现范围闭包。 这是一个非常简单的代码,但它不起作用。 这段代码的主要思想是使用功能“增加”按钮事件中“点击”,然后显示在DIV结果:显示关闭HTML页面
(function() {
'use strict'
var showIncrease = document.getElementById("increase").innerHTML;
this.increase= function (strat) {
return function() {
start++;
return start;
}
}
var inc = increase(0);
showIncrease = inc;
}).apply(this);
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<button onclick="inc()">increase</button>
<div id="increase"></div>
<script src="timer.js"></script>
</body>
</html>
答
在您的示例inc
功能是函数作用域的局部变量。您可以在该函数内部使用它,例如在increase
中使用start
,但不能从函数作用域之外访问它。按钮上的onclick会尝试在全局范围(窗口)中访问它,所以它无法找到该功能。但是,它可以找到increase()
。
如果将var inc = increase(0);
更改为this.inc = increase(0);
,则inc
变量将位于全局作用域(窗口对象)中。这将使onclick能够找到它。
即使这样它不会显示div内的结果,你只是分配变量showIncrease
与功能inc
,它不会更新HTML的方式。
要更新div的内容,你可以换你inc
功能,增加和更新内容:
var divIncrease = document.getElementById("increase");
var inc = increase(0);
this.incAndShow = function() {
var result = inc();
divIncrease.innerHTML = result;
}
而在你的HTML调用该函数来代替:
<button onclick="incAndShow()">increase</button>
它终于做到了,谢谢 – Ilanz