I have data Json in aray. and I de-serialize in ajax. I want to change the class from element if it has class 'Booked'. is it efficient to write like this ?
$.ajax({
url: "URL.aspx/GetData",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
objData = new Array();
objData = arr;
for (i = 0; i < objData.length; i++) {
if (jQuery('#' + objData[i].noSeat).hasClass('seat-booked'))
{
jQuery('#' + objData[i].noSeat).addClass('seat-availiable');
jQuery('#class-' + objData[i].noSeat).attr('value', 'seat-availiable');
jQuery('#' + objData[i].noSeat).removeClass('seat-booked');
jQuery('#' + objData[i].noSeat).removeClass('selected');
}
}
I put
if
statement in
for
looping. I want to make it faster to processed. is it the best way ?
You could try for I in
for (var I in objData) {
objData[I] // stuff
}
Edit: fixing my mistake, if only phones had autocorrect. I only meant that I think for-in loops are better than for i = 0; i < length; i++ style loops.
To make it up i'll try suggesting this untested code and downvote me if it fails :)
for (i in objData) {
jQuery('#' + objData[i].noSeat + '.seat-booked')
.addClass('seat-availiable')
.removeClass('seat-booked selected')
.closest('#class-' + objData[i].noSeat)
.val('seat-availiable');
}
for-in looks at each element in the objData and is similar to the i=0; i<l; i++; but seems like it makes fewer assignments. the Jquery('selector') can take multiple conditions and if there's no space between the ID and the class like '#' + objData[i].noSeat + '.seat-booked', it needs both to return the object. Then all the add/remove stuff can be added to the returned object. If there's no object returned nothing else in the chain can execute, so nothing happens.