سؤال

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