javascript - Javascript 中的闭包和 onclick

标签 javascript html closures

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

相关文章:

javascript - IBM Watson Conversation - Angular 集成

javascript - 如何在 false 时触发函数?

javascript - 带有 SPServices + jQuery 的 CORS

javascript - 如何在 Bootstrap 导航栏中排列图像和文本的底部?

Swift 在不放弃隐式参数的情况下关闭 : Is it possible to specify the return type,?

rust - Rust-从 `&str`转换为 `String`,然后使用闭包转换

javascript - 如何使用 HTML5、JS 或 Angular 验证 Ionic 中的电子邮件?

javascript - 我如何为无法设置动画的内容进行缓慢过渡?

javascript - 使用 jQuery .append 时,子级的父级不会得到更新

swift - 你能帮我理解这个 Swift 方法吗?