JQuery heavy concatenation

Consider the following piece of code about the Twitter API. data.followers_count

didn't work if placed in anchor labels. There's some simple concatenation problem that I can't fix because of the many parentheses. Any help is appreciated.

function(data){
   $('#twitter').html( document.getElementById('twitter').innerHTML + twitterusername[i] + ' ' +
   <a href='someURL' title='someTitle'>data.followers_count</a> + ' Followers' + '<br/>');
}

      

+3


source to share


3 answers


just break them down into simple parts

function(data) {

    //twitter container and it original HTML
    var twitter = $('#twitter');
    var twitterHTML = twitter.html();

    //your link
    var link = $('<a></a>').attr('href', 'someUrl').text(data.followers_count);

    //everything in an array and joined into a string
    var newHtml = [twitterHTML, twitterusername[i], ' ', link, ' Followers<br/>'].join('');

    //put back in
    twitter.html(newHtml);
}​

      

and presto! no concatenations and no plus signs!




alternatively a much shorter solution (I just cleaned up the code and didn't notice it was an add operation):

function(data) {

    //build the link
    var link = $('<a></a>').attr('href', 'someUrl').text(data.followers_count);

    //build the HTML
    var newHtml = [twitterusername[i], ' ', link, ' Followers<br/>'].join('');

    //append HTML
    $('#twitter').append(newHtml);
}​

      

+2


source


Not sure if you accidentally posted the code with missing quotes, but your best guess is what you posted.



function(data)
{
    $('#twitter').append( twitterusername[i] + 
      "<a href='someURL'title='someTitle'>" +
      data.followers_count + "</a> Followers<br/>");
}

      

+5


source


I don't know if the copy and paste was lost, but you don't quote the tag a

, it should be something like:

function(data) {
   $('#twitter').html( document.getElementById('twitter').innerHTML + twitterusername[i]
     + ' ' + "<a href='someURL' title='someTitle'>" + data.followers_count
     + '</a> Followers<br/>');
}

      

+3


source







All Articles