Dynamically creating elements using jQuery -
i building list of checkbox items in jquery based on array returned handler.
the containing element .listcontainer
element below , each dynamic element want add takes form of .listcontaineritem
element. each item have checkbox value , label based on array item creating it.
<div class="listcontainer"> <div class="listcontaineritem"> <input type="checkbox" value="1" /> <div class="listcontaineritemlabel">checkbox 1</div> </div> </div>
at point of function has array passed it, efficient way of creating this? have been trying accomplish below, running major performance issues.
function additemtolistcontainer(item) { var currentitems = $j("#listcontaineravailable .listcontaineritem"); if ($j.grep(currentitems, function (e) { return $j(e).find(":checkbox:first").val() == item.id; }).length === 0) { labeldiv = $j("<div />").addclass("listcontaineritemlabel").html(item.text); itemtoadd = $j("<div />").addclass("listcontaineritem").append("<input type=\"checkbox\" value=\"" + item.id + "\" />").append(labeldiv); currentitems.append(itemtoadd); } }
i've looked @ .map
function, not sure quite how implement it. can point me in right direction?
i start this:
var $container = $j('#listcontaineravailable'); var checkboxes = {}; function additemtolistcontainer(item) { if (checkboxes[item.id]) return false; checkboxes[item.id] = true; var $item = $j('<div />', { 'class': 'listcontaineritem', }).appendto($container); $j('<input />', { 'type': 'checkbox', 'value': item.id }).appendto($item); $j('<div />', { 'class': 'listcontaineritemlabel', 'text': item.text }).appendto($item); }
as long none of these elements exist when create page, can add them hash table instead of searching through dom. think you'd benefit js templating engine mustache.js
Comments
Post a Comment