通过jQuery实现后无法显示每个帖子的数据

时间:2014-05-13 07:01:40

标签: jquery json

这是我首先实现Facebook和Twitter股票计数的小提琴

http://jsfiddle.net/v8gw6/1/

它运作良好,但后来我在多个帖子上尝试了它没有响应,这是第二小提琴。 http://jsfiddle.net/v8gw6/3/

这是我在第二小提琴中使用的代码 的 HTML

<div class='post'>
    <div class='sharing-bar' data-href='http://www.bloggerever.com/2014/05/codeanywhere-most-useful-and-multi.html'>
<span class='sum'></span>

<span class='facebook'></span>

<span class='twitter'></span>

    </div>
</div>
<div class='post'>
    <div class='sharing-bar' data-href='http://www.bloggerever.com/2014/05/which-blog-type-suites-you-best-head-to.html'>
<span class='sum'></span>

<span class='facebook'></span>

<span class='twitter'></span>

    </div>
</div>

Jquery的

$(function () {
    $('.post').each(function () {
        var url = $(this).find('.sharing-bar').attr('data-href');
        var fburl = "http://graph.facebook.com/?id=" + url;
        $.getJSON(fburl, function (data) {
            if (data["shares"] != undefined) {
                var fbshares = data["shares"];
            } else {
                var fbshares = 0;
            }
            $(this).find(".sharing-bar .facebook").append(fbshares);
            var url = $(this).find('.sharing-bar').attr('data-href');
            var twitterurl = 'http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?';
            $.getJSON(twitterurl, function (data) {

                var twittershares = data["count"];
                $(this).find(".sharing-bar .twitter").append(twittershares);
                var sumofboth = fbshares + twittershares;
                $(this).find(".sharing-bar .sum").append(sumofboth);
            });

        });
    });
});

请帮忙

1 个答案:

答案 0 :(得分:1)

您的this引用存在问题,因为此引用在getJson方法中发生更改,但未指向post div,因此无法找到.facebook span < / p>

见下文

$('.post').each(function () {
    var url = $(this).find('.sharing-bar').attr('data-href');
    var fburl = "http://graph.facebook.com/?id=" + url;
    // here this is .post object
    var $this= $(this);
    $.getJSON(fburl, function (data) {
        var fbshares = 0;
        if (data["shares"] != undefined) {
            fbshares = data["shares"];
        }
        // here this is not .post object, so store .post object in variable $this and use it.
        this.find(".sharing-bar .facebook").text(fbshares); // it will not work.
        $this.find(".sharing-bar .facebook").text(fbshares); // it will work
    });

    // rest of your code goes here
});