我有一个在 this jsfiddle 上冒泡的 Javascript 事件的简单示例(点击那个人,它会冒泡到 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;
}
最佳答案
您可以将函数包装在另一个函数中以形成闭包。但是由于您有两个函数要绑定(bind)到同一个闭包,因此您需要一个对象。
检查一下 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>
关于javascript - Javascript 中的闭包和 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36276396/