I'm on the road to prepare for the 70-480 Microsoft exam and I'm learning the basics of jQuery.
Now I wrote the following JavaScript function to create a table dynamically:
function MakeTableJavascript() {
var rows = document.getElementById("rows").value;
var cols = document.getElementById("cols").value;
var placeholder = document.getElementById("placeholder");
var table = document.createElement("table");
table.setAttribute("border", "1");
for (var r = 0; r <= rows; r++) {
var row = document.createElement("tr");
for (var c = 0; c < cols; c++) {
if (r == 0) {
var head = document.createElement("th");
var texthead = document.createTextNode("Column " + c);
head.appendChild(texthead);
row.appendChild(head);
}
else {
var col = document.createElement("td");
var textrow = document.createTextNode(c.toString() + r.toString());
col.appendChild(textrow);
row.appendChild(col);
}
}
table.appendChild(row);
}
placeholder.appendChild(table);
}
Then I re-wrote the same function with jQuery:
function MakeTablejQuery() {
var rows = $('#rows').val();
var cols = $('#cols').val();
var placeholder = $('#placeholder').val();
var table = document.createElement("table");
$('table').attr("border", 1);
for (r = 0; r <= rows; rows++) {
var row = document.createElement("tr");
for (var c = 0; c < cols; c++) {
if (r == 0) {
var head = document.createElement("th");
var texthead = document.createTextNode("Column " + c);
head.appendChild(texthead);
row.appendChild(head);
}
else {
var col = document.createElement("td");
var textrow = document.createTextNode(c.toString() + r.toString());
col.appendChild(textrow);
row.appendChild(col);
}
}
table.appendChild(row);
}
placeholder.appendChild(table);
}
The result in term of lines of written code is practically the same.
Surely I can use jQuery in a better way to write less code, but at the actual state I have no idea on how to do so.
Can anyone more experienced in jQuery give me a suggestion to narrow the above code?
$
somewhere does not mean you're using jQuery to its full potential. I don't see an answerable question here. – deceze Jul 21 '13 at 10:03r
, which mean you were falling prey to The Horror of Implicit Globals, and the fact you were trying to useappendChild
on the value held by#placeholder
, rather than on#placeholder
). – T.J. Crowder Jul 21 '13 at 10:09