문제

I'm trying to create a counter via a closure using javascript for all links clicked on a page. This is what I have so far, but it is using a global variable. How do I modify this, using a closed variable?

var count = 0;
$('body').on('click', '.a', function() {  
    count++;
    console.log(count)
})
도움이 되었습니까?

해결책

You can create an IIFE around it:

(function(){ 
  var count = 0;
  $('body').on('click', '.a', function() {  
    count++;
    console.log(count)
  });
})();

Javascript has function scoping, so count will be local to that outer anonymous function.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top