1

i am trying to generate html for the json returned array of users.. I want to do it the following way but I don't feel this is very effecient way to do this job. please review the following code and tell me whether i sould use some templated code or is there any standard for this scenario?

                  success: function(e){
       console.log(e);
       console.log(e.d[0].UserName);

       var position2= $("#searchtextbox").position();
       $('<div/>',
        {
          id:'generatedsearchdiv', 
          css:{
              position:'absolute',
              left:position2.left, 
              top:position2.top+20
              }

         }).appendTo('#searchArea');

       for (var i=0; i<=e.d.length; i++)
       {
       $('<div/>', 
            {

            html:"<span>"+e.d[i].UserName+"<span>"
            }).appendTo('#generatedsearchdiv');

       }

       } 
Spirals Whirls
  • 543
  • 1
  • 8
  • 27

3 Answers3

0

You can go with Jquery templates for this..

0

This method is "okay" for small bits of HTML, like <span>{data}</span>. However, if you have much more than that, it really is best for maintainability to use a templating solution. Check out this answer for options.

Community
  • 1
  • 1
Dave Thieben
  • 5,388
  • 2
  • 28
  • 38
0

I have not been sold on the current templating solutions. If you aren't either, you can get a quick string formatter if you put this code inline:

String.prototype.format = function() {
    var pattern = /\{\d+\}/g;
    var args = arguments;
    return this.replace(pattern, function(capture) {return args[capture.match(/\d+/)]; });
}

You can define formatting strings like so:

var formatHTML = '<span>{0}</span>';

Then use it something like this:

$('#generatedsearchdiv').append(formatHTML.format(e.d[i].UserName));
Chris Broski
  • 2,421
  • 27
  • 23