Beyond a for, I declare a variable with var list;. I use this variable inside a for loop like this:
if (list == undefined)
list = item;
else
list.append(item.contents());
itemis the cloned jquery object from the call $('list_template').clone();(list_template is a div element with <li>inside). What I am doing is creating a list, which I will appendTo () where I need it.
This code is currently working fine, but it doesn't seem right to me. Unfortunately, I cannot figure out how to correctly declare a variable as listan empty jQuery object. I tried both:
var list = $([]);
var list = $('');
Both of them cause append to work incorrectly (or as expected) with list.html () being null. Is there a way to initialize my variable for an empty jquery object, so all I have to do is list.append(item.contents());without if / else statements?
Edit: Well, to reduce confusion, here is the whole javascript function that currently works fine: var list;
var objects = data.objects;
for (x = 0; x < objects.length; x++) {
var item = $("#object_item_list_template").clone();
item.find('a').bind('click', { val: objects[x].Id }, function (e) { ShowObjectDetails(e.data.val); })
.html(objects[x].Name);
if (list == undefined)
list = item;
else
list.append(item.contents());
}
$("#object_list").empty();
$('<ul>').appendTo("#object_list").append(list.contents());
The object list template is as follows:
<div id="object_item_list_template" style="display:none">
<li class="object_item"><a href="#"></a></li>
</div>
All this works correctly, cloning the list item, customizing the action of the click and adding it to the list on the display.
I am trying to get rid of the if / else statement. I can't just do list.append (), because if the list is undefined (or not a jQuery object), it throws an exception.