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

function closure show up variable of outer function

您好,我正在尝试关闭,但不知道如何在点击图片之前打印出“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>

几点建议:

  1. 切勿将标记与 javascript
  2. 混合使用
  3. 尝试处理 javascript
  4. 的事件
  5. 您不需要闭包,因为 this.You 可以在标记上设置 10 个赞,然后单击继续增加值

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

希望对您有所帮助