user580801
user580801

Reputation: 3

Jquery Twitter Parse Json

I have this issue, where everything is working more or less but its giving me too many results.

Any idea?

var url = "search.twitter.com/search.json?q=%23ps3&rpp=15&from=mmgn&lang=en&callback=?";
$.getJSON(url, function(data) {
    $.each(data.results, function(i, item) {
        var tweet = item.text;
        var combinedRegex = /[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+|[@]+[A-Za-z0-9-_]+|[#]+[A-Za-z0-9-_]+/g,
            container = $('#tweet-container');
        var result, prevLastIndex = 0;
        combinedRegex.lastIndex = 0;
        while ((result = combinedRegex.exec(tweet))) {
            $('').appendTo('#tweet-container');
            $('').html(tweet.slice(prevLastIndex, result.index)).appendTo('.tweet');
            if (result[0].slice(0, 1) == "@") {
                $('').attr('href', 'http://twitter.com/' + encodeURIComponent(result[0].slice(1))).html(result[0]).appendTo(".tweet");
            } else if (result[0].slice(0, 1) == "#") {
                $('').attr('href', 'http://search.twitter.com/search?q=%23' + encodeURIComponent(result[0].slice(1))).html(result[0]).appendTo('.tweet');
            } else {
                $('').attr('href', result[0]).html(result[0]).appendTo(".tweet");
            }
            prevLastIndex = combinedRegex.lastIndex;
        }
        $('').append($('').html(tweet.slice(prevLastIndex)));
    });
});

Hyperlink, below

Upvotes: 0

Views: 1271

Answers (1)

bluescrubbie
bluescrubbie

Reputation: 540

You've got a couple of issues here: appending your li elements and inserting your 'first'/'last' span elements.

1) you're calling .appendTo(".tweet"), which is selecting ALL elements with the tweet class. Instead, create an variable for the li element, and then append your data to that variable, eg.

var $li = $('<li class="tweet" />');
$li.appendTo('#tweet-container');
...
$('whatever').appendTo($li);

2) On your span elements, you are also appending to ALL .tweet elements (as above). It appears you want to add a span element only to the first and last item in your list. If this is the case, I'd suggest waiting until the loop is done and then wrapping the first and last elements like:

$('li',container).first().wrapInner('<span class="first"/>').end().last().wrapInner('<span class="last"/>');

Here's the changed code.

You could also stand to make your jquery a bit more efficient, but that's beyond the scope of your question.

Upvotes: 0

Related Questions