I am new to jquery, and after spending weeks to convert my pages using jquery, now I am reading about jquery optimization. In that effort, I rewrite one of my functions like below. Appreciate if you comment whether it is write (both are working btw). Also any further improvement tips would be helpful.
PREVIOUS CODE
$("#mydiv").empty();
var i = 2;
$("#axisa option").each(function() {
$("#mydiv").append("<div id='tempdiv"+i+"'></div>");
updateCharts($("#wd").slider("value"), $("#ht").slider("value"),$(this).val());
i++
});
$("#axisb option").each(function() {
$("#mydiv").append("<div id='tempdiv"+i+"'></div>");
updateCharts($("#wd").slider("value"), $("#ht").slider("value"),$(this).val());
i++
});
$("#hiddendiv").show("slow");
OPTIMIZED CODE
var mydiv = $("#mydiv");
var mywid = $("#wd").slider("value");
var myhet = $("#ht").slider("value");
var total = $("#axisa option").length + $("#axisb option").length+2;
mydiv.empty();
var design = "";
for(var i=2;i<total;i++){
design += "<div id='tempdiv"+i+"'></div>";
}
mydiv.append(design);
i = 2;
$("#axisa option").each(function() {
updateCharts(mywid, myhet, $(this).val());
i++
});
$("#axisb option").each(function() {
updateCharts(mywid, myhet, $(this).val());
i++
});
$("#hiddenDiv").show("slow");
mydiv
as a variable, but then you still use$('#mydiv')
. Could you throw this up into a jsFiddle with some target HTML? I'm not quite clear on what you are trying to do. – Michael Paulukonis Jan 28 '13 at 19:36$("#mydiv").append(design)
when you could have usedmydiv.append(design)
. Larger picture though -- I don't know what your code is trying to accomplish. – Michael Paulukonis Jan 28 '13 at 20:30