tags:

views:

1079

answers:

4
+2  A: 
$.each(data, function (i, item) {
    $('ul').append('<li><a href="yourlink?id=' + item.UserID + '">' + item.Username + '</a></li>');
});
RaYell
watch out for malicious HTML injection when you use this technique
Philippe Leybaert
Its also not the best route. Appending to the dom multiple times causes mass redraws. Better to do this once.
redsquare
+1  A: 
$.each(data, function(i, item) {

       var li = $("<li><a></a></li>");

       $("#yourul").append(li);

       $("a",li).text(item.Username);
       $("a",li).attr("href", "http://...." + item.UserID);

    }
Philippe Leybaert
+1  A: 

Get the <ul> using jQuery selector syntax and then call append:

$("ul#theList").append("<li><a href='url-here'>Link Text</a></li>");

See jQuery docs for more information.

krohrbaugh
if you have the id use it alone. Dont prefix the nodeName, slower.
redsquare
Yeah I know, I was just trying to be expressive here since no ID was provided in the question.
krohrbaugh
redsquare
+6  A: 

The most efficient way is to create an array and append to the dom once.

You can make it better still by losing all the string concat from the string. Either push multiple times to the array or build the string using += and then push but it becomes a bit harder to read for some.

Also you can wrap all the items in a parent element (in this case the ul) and append that to the container for best performance. Just push the '<ul>' and '</ul>' before and after the each and append to a div.

   var items = [];

   $.each(data, function(i, item) {

          items.push('<li><a href="yourlink?id=' + item.UserID + '">' + item.Username + '</a></li>');

   }

   $('#yourUl').append( items.join() );
redsquare
i like this idea, one append.
mrblah
Excellent answer. +1
bryan
Does this have injection issues like another comment stated?
mrblah
Do you trust your source? Do you have control over the json or is it from a third party? What do the links do. Can they delete from the links? Lots of good articles on google. Start with this one http://yuiblog.com/blog/2007/04/10/json-and-browser-security/
redsquare
I am the source, so I trust myself :)
mrblah
In jQuery 1.4.3 you have a new thing called "tmpl". It's worth the look: http://api.jquery.com/tmpl/
Nordes
@Nordes - yeah - this was well before 1.4.3!
redsquare
@redsquare This is now a part of the API (see the comment on the JQuery page : version added: 1.4.3)
Nordes
@Nordes.......eh? This answer was from Jul 2009. I know .tmpl is part of 1.4.3 but cannot go through and amend all jquery answers in support of this!
redsquare