函数闭包显示外部函数的变量

时间:2016-10-21 00:04:10

标签: javascript counter

您好我正在尝试关闭,但无法弄清楚如何打印出来" 10喜欢"点击图片之前?是否有人可以帮我一些帮助我?



var clickCount = (function() {
	var clickCounter = 10; //start from 10 likes
	return function() {
		var amountOfLikes = document.getElementById("counter");
		amountOfLikes.innerHTML =  clickCounter + " likes"; //increment the likes
		clickCounter++;
	}
})();

  <img src="http://image.flaticon.com/icons/png/128/148/148836.png" id="like_button" alt="like-button" onclick="clickCount()"/><span id="counter"></span>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

一些建议:

  1. 永远不要将标记与javascript混合
  2. 尝试在javascript上处理事件
  3. 你不需要关闭它。你可以在标记上设置10个喜欢,然后只需点击继续增加值
  4. window.onload = function() {
      document.getElementById("counter").addEventListener('click', clickCount);
    }
    
    function clickCount() {
      var amountOfLikes = document.getElementById("counter");
      var likes = parseInt(amountOfLikes.innerHTML, 0);
      amountOfLikes.innerHTML = likes + 1;
    }
    <img src="http://image.flaticon.com/icons/png/128/148/148836.png" id="like_button" alt="like-button" onclick="clickCount()"/><span id="counter">10 </span> likes

    希望这有帮助