I think JQuery is great but I also like the idea of keeping the HTML in the HTML document and virtually none of it in the javascript. What do I mean? You know like, say you are creating a dynamic table that had many many rows or a variable number of rows. This is exactly what I DON'T want to do:
function initBoard(symbol) {
for (var i=0;i<30;i++) {
myBoard += "<tr>";
enemyBoard += "<tr>";
for (var j=0;j<60;j++) {
myBoard += '<td bgcolor="#0000ff" id="my_sqr_'+i+'_'+j+'">'+symbol+</td>';
enemyBoard += '<td bgcolor="#ff0000" id="enemy_sqr_'+i+'_'+j+'">'+symbol+'</td>';
}
myBoard += "</tr>";
enemyBoard += "</tr>"
}
$("#my-board").html(myBoard);
$("#enemy-board").html(enemyBoard);
}
A few years ago I came up with a solution that almost works well and I frequently use it but I'd still like to see something better and that's what my question is about. My current strategy is to create a hidden div at the bottom of the main HTML file. For example:
<div class="hidden-templates" style="visibility:hidden;">
<div id="board-line-tpl">
<td bgcolor="--bg-color--" id="--side--_sqr_--index1--_--index2--">--symbol--</td>
</div>
</div>
and then the javascript is changed to something like this:
function initBoard(symbol) {
for (var i=0;i<30;i++) {
myBoard += "<tr>";
enemyBoard += "<tr>";
for (var j=0;j<60;j++) {
// Get the template
myBoardLine = $("#board-line-tpl").html();
// substitue the template's"variables" with unique data
myBoardLine.replace(/--side--/, "my");
myBoardLine.replace(/--bg-color--/, "#0000ff");
myBoardLine.replace(/--index1--/, i);
myBoardLine.replace(/--index2--/, j);
myBoardLine.replace(/--symbol--/, symbol);
myBoard += myBoardLine;
// You get the idea. I'll leave this line as is.
enemyBoard += '<td bgcolor="#ff0000" id="enemy_sqr_'+i+'_'+j+'"></td>';
}
myBoard += "</tr>";
enemyBoard += "</tr>"
}
$("#my-board").html(myBoard);
$("#enemy-board").html(enemyBoard);
}
OK, one thing you notice that sucks about my solution is quite a bit more verbose but in fairness, it does seem to shine if your template has any sort of complexity. A good candidate for a template is HTML having 5 or more lines. Another thing in it's favor is it does do the job of getting HTML out of the Javascript. Now I can let my HTML designer edit the HTML in the hidden-template div, and change the look of it and put classes in as desired (It was easy to teach him about the templates and what they do) and so now he doesn't have to touch the Javascript. However, lately I've been running into some problems with defining whole tables as a template. As JQuery reads the template it tries to reinterpret the table code and it screws it up.
jQuery provides a syntax where you can specify attributes at the time of element creation. This should provide the clean look you want.
You may also want to look into storing the board x/y attributes in a data object as opposed to embedded in the id.
Here is an example based on your code:
http://jsfiddle.net/YAHDK/