Javascript中的闭包和onclick

Closures and onclick in Javascript

本文关键字:onclick 闭包 Javascript      更新时间:2023-09-26

我有一个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>