I'm new to jQuery, and am using it to dynamically construct chunks of a page.
The created HTML is what I want, but I'm not sure if the way I'm generating it is sensible or idiomatic.
function setupIndex()
{
$(document.body).append($("<img/>", {src : 'logo.png'}));
var div = $("<div/>", {"class" : "content"}).appendTo(document.body);
div.append("<h2/>", { text :'My Panels'});
div.append($("<table/>", {id : 'maintable'}));
}
function addPanel(name, desc)
{
if (!$("#maintable"))
setupIndex();
var row = $("<tr/>",{"class":"panels"}).appendTo("#maintable");
var div = $("<td/>").appendTo(row);
div.append($("<h3/>").append($("<a/>", { text : name, href : name + "/index.html"})));
div.append(document.createTextNode(desc));
div = $("<td/>").appendTo(row);
var anc = div.append($("<a/>", {href: name + "/index.html"}));
anc.append($("<img/>", { css : {width : "200px", height : "auto"}, src : name + "/thumbnail.png"}));
}
1 Answer 1
I know that the following might seem crazy at first but humour me for a minute. The main improvement is so that variables are not reused (which confuses their meaning) and the subtle .appendTo("#maintable")
is at the end (which means the document is altered once).
There is not functional need to store the objects into variables as they aren't re-used. I often try to write in this pattern as it looks more like the way you'd write html.
if (!$("#maintable"))
setupIndex();
$("<tr/>", {"class":"panels"})
.append(
$("<td/>")
.text(desc)
.prepend(
$("<h3/>")
.append($("<a/>", { text : name, href : name + "/index.html"})))
)
)
.append(
$("<td/>")
.append($("<a/>", {href: name + "/index.html"}))
.append($("<img/>", { css : {width : "200px", height : "auto"}, src : name + "/thumbnail.png"}))
)
.appendTo("#maintable");
-
\$\begingroup\$ I've just found a StackOverflow question similar: stackoverflow.com/questions/9760328/… \$\endgroup\$James Khoury– James Khoury2013年12月04日 02:52:26 +00:00Commented Dec 4, 2013 at 2:52
-
1\$\begingroup\$ Your first conditional won't work as expected:
$()
always returns a jQuery object (i.e. something truth'y) regardless of whether it finds an element, sosetupIndex()
will never be called. You'll want to checkif($('#maintable').length === 0)
(or, shorter,if(!$('#maintable').length)
) \$\endgroup\$Flambino– Flambino2013年12月04日 13:23:46 +00:00Commented Dec 4, 2013 at 13:23 -
\$\begingroup\$ @Flambino. Yup, you're right. I hadn't spotted that. \$\endgroup\$Roddy– Roddy2013年12月04日 21:07:09 +00:00Commented Dec 4, 2013 at 21:07
-
\$\begingroup\$ @JamesKhoury - Thanks. What about
$("<td/>")
vs.$("<td>")
? Either seems to work... \$\endgroup\$Roddy– Roddy2013年12月04日 21:10:02 +00:00Commented Dec 4, 2013 at 21:10 -
1\$\begingroup\$ @Roddy I am not sure jQuery sees any difference between
$("<td/>")
and$("<td>")
\$\endgroup\$James Khoury– James Khoury2013年12月05日 00:49:42 +00:00Commented Dec 5, 2013 at 0:49