简体   繁体   中英

Facebook like count with jQuery

I'm having a little problem: I'm trying to write a jQuery function that loops over all divs which have a specific class and populates them with Facebook's Like count (the required URL is in the rel attribute). The problem is that it only takes effect on the last item for some reason.

HTML:

<div class="facebook_likes" rel="http://www.somesite.com/"></div>
<div class="facebook_likes" rel="http://www.somesite2.com/"></div>
<div class="facebook_likes" rel="http://www.somesite3.com/"></div>

JS:

function getLikes() {
    jQuery('.facebook_likes').each(function(){
    currentdiv = jQuery(this);
        url = currentdiv.attr('rel');
    jQuery.getJSON('http://graph.facebook.com/'+url,function(data) {
       currentdiv.text((data.shares || 0)+' Likes');
    });
})

}

Thanks!

PS: I'm calling the function on document ready. Fiddle at: http://jsfiddle.net/Mjzpm/1/

The answer is very simple.

function getLikes() {
    jQuery('.facebook_likes').each(function(){
        var currentdiv = jQuery(this);
        var url = currentdiv.attr('rel');
        jQuery.getJSON('http://graph.facebook.com/'+url,function(data) {
           currentdiv.text((data.shares || 0)+' Likes');
        });
    })
}

You need to initialize currentDiv and url on every loop through. By the time the first getJSON completes, the currentDiv/url are now equal to the last value that those two variables were set to.

At first you have to create a username of your page(see under your page name @username. Just click it...)

Then goto https://developers.facebook.com/tools/explorer/ and get an access token key

Then script something like that

function facebookLikesCount(access_token)
{
var url = "https://graph.facebook.com/voucherin.ukbd?fields=likes&access_token="+access_token+"";

$.getJSON(url,function(json){
alert(json.likes);
});
}

facebookLikesCount('your accesstoken');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM