There is a maintanble approach to build DOM with jQuery?
Take a look at the append method of this code…
$.getJSON("api/test", function(data) {
$.each(data, function () {
$("#tests").append($('<tr><td><input type="radio" name="' + this["name"] + '"/><td>' + this["name"] + '</td><td>' + this["descr"] + '</td></tr>'));
});
});
I think (or at least I hope) there’s a better way. Can you refactor this to be more legible?
Look at the template plugin.
http://plugins.jquery.com/project/jquerytemplate
Your code can now look like,
EDIT
As redsquare correctly points out, if you have large number of rows, doing DOM manipulation in each iteration can be really slow. Don’t change your code unless you have profiled your code and found this particular loop to be the bottleneck.
If I borrow the ‘string.Format’ method from this post, you can do something like
EDIT: Modified the string.Format function to take name based key. Now your template code can use {name}, {descr} instead of using {0}, {1}. The function will try to find the property with the same name in the argument passed to the function.
Also, look at Rick Strahl’s approach and see if it makes more sense to you.
http://www.west-wind.com/WebLog/posts/300754.aspx