I want to parse the data from a json and replace them in a table. And I’m using following code
var obj=$.parseJSON(data);
data=obj.data;
totalRecord=obj.totalCount;
$.each(data,function(i,obj){
for(var j in obj){
switch(j){
case 'priority':
$("#td_"+i+"_"+j).find('.priority').val(obj[j]);
$("#td_"+i+"_"+j).find('.hidden').val(obj['id']);
break;
case 'chkbox':
$("#td_"+i+"_"+j).find('.chkbox').val(obj['id']);
break;
case 'status':
var val=(this.j)?'active.gif':'deactive.gif';
$("#td_"+i+"_"+j).find('img').attr('src','<?= base_url() ?>assets/grid/images/'+val);
$("#td_"+i+"_"+j).find('img').attr('onClick','updateStatus(\''+obj['id']+'\',\''+obj[j]+'\')');
break;
case 'edit':
$("#td_"+i+"_"+j).find('a').attr('href','index.php/main/edit/'+obj[j]);
break;
default:
$("#td_"+i+"_"+j).html(obj[j])
break;
}
}
});
But i think its bit slow. Is there other better ways to implement the same?
KrishNik
I’m not sure it’s the parsing that’s slowing you down. It could be that you’re running a lot of jQuery selectors on a lot of objects, which can take time.
EDIT: Saw @pointy’s answer. I didn’t even notice that you were doing event delegation via DOM attributes. Yeeaah, that would probably run pretty slowly.
In fact, using
liveevent delegation instead of assigning a click event to every single element would probably run even faster. Start by, instead of giving it the click event, give the element a reference to the object in question using jQuery’sdatafunction.Then, run the following only once in your entire script (obviously, untested).
This means that any
imginside atd.statuselement (yep, I made up a new class name for you) that ever exists will, upon being clicked, runupdateStatuswith thatstatus_objdata stored inside it.Some smaller optimizations:
find('span.priority'), since jQuery can then loop through only children of that tag name instead of all childrengetElementByIdis almost certain to run faster than looping through children.