Javascript中的闭包和onclick
Closures and onclick in Javascript
我有一个Javascript事件在这个jsfiddle上冒泡的简单例子(点击man,它就会冒泡到pig)。如何使用闭包将var interval = 0;
从全局范围中移除,但在html中保留onclick="display('sometext')"
?
var interval = 0;
function display(animal) {
window.setTimeout(function() { showText(animal) }, interval);
interval = interval+300;
window.setTimeout(function() { clear() }, interval);
}
function showText(animal) {
$(".alGore").text(animal.toUpperCase());
$("."+animal+"-box").css({'background-color':'#ff0'});
}
function clear(animal) {
$(".alGore").text('');
$("*").css({background: 'transparent'});
interval = 0;
}
您可以将函数包装在另一个函数中以生成闭包。但是,由于有两个函数要绑定到同一个闭包,因此需要一个对象。
看看这个https://jsfiddle.net/axrpcaq4/16/:
var animalBox = function(){
var interval = 0;
return {
display: function(animal) {
var that = this;
window.setTimeout(function() { that.showText(animal) }, interval);
interval = interval+300;
window.setTimeout(function() { that.clear() }, interval);
},
showText: function(animal) {
$(".alGore").text(animal.toUpperCase());
$("."+animal+"-box").css({'background-color':'#ff0'});
},
clear: function(animal) {
$(".alGore").text('');
$("*").css({background: 'transparent'});
interval = 0;
}
}
}();
和HTML:
<div class="center">
<div class="pig-box center" onclick="animalBox.display('pig')">
<img src="http://i.imgur.com/MumugGd.png" alt="pig" class="icon">
<div class="bear-box center" onclick="animalBox.display('bear')">
<img src="http://i.imgur.com/p7L5DHL.png" alt="bear" class="icon">
<div class="man-box center" onclick="animalBox.display('man')">
<img src="http://i.imgur.com/cKvJT7T.png" alt="man" class="icon">
</div>
</div>
</div>
<div class="alGore"></div>
</div>
相关文章:
- 在underscorejs模板中使用闭包
- setTimeout可以与闭包内的函数一起使用吗
- 附加到原型属性的Do函数没有闭包
- 使用闭包共享构造函数参数
- 使用Google闭包编译器包含一个Ecmascript 6类
- 从js引擎的角度来看闭包和构造函数是如何工作的
- for循环中的JavaScript闭包
- Javascript闭包-如何防止内存泄漏
- 子类访问父类's闭包变量
- 闭包如何具体化数据封装
- Javascript.闭包和dynamic'这'实际上具有约束力
- 构造函数函数闭包变量
- 闭包js框架-将ArrayBuffer转换为字符串
- 如何在Angularjs中重构闭包中的重复代码
- 如何告诉闭包javascript编译器不要混淆webkitAudioContext的方法名称
- Google闭包和生成的getters/ssetter
- 如何冻结函数's在闭包中的变量
- 未使用JS闭包将变量传递给onClick函数
- Javascript中的闭包和onclick
- jQuery / javaScript - click / onclick事件监听器不工作,尽管闭包内循环