Outside of a for I declare a variable using var list;. I use this variable inside of my for loop like so:
// add the html to the list
if (list == undefined)
list = item;
else
list.append(item.contents());
item is a cloned jquery object build from a $('list_template').clone(); call (list_template is a div with <li> elements inside). What I am doing is creating a list, which I will then appendTo() where I need it.
Right now this code works fine, but it doesn’t seem right to me. Unfortunatly, I cannot seem to figure out how to correctly declare the list variable to be an empty Jquery object. I have tried both:
var list = $([]);
var list = $('');
Both of those cause the append to not work correctly (or as expected) with list.html() being null. Is there a way to initialize my variable to an empty jquery object, so all I have to do is list.append(item.contents()); without the if/else statements?
Edit: Ok to lessen confusion here is the whole javascript function that currently works fine:
var list;
// Loop through all of the objects
var objects = data.objects;
for (x = 0; x < objects.length; x++) {
// Clone the object list item template
var item = $("#object_item_list_template").clone();
// Setup the click action and inner text for the link tag in the template
item.find('a').bind('click', { val: objects[x].Id }, function (e) { ShowObjectDetails(e.data.val); })
.html(objects[x].Name);
// add the html to the list
if (list == undefined)
list = item;
else
list.append(item.contents());
}
// set the list of the topics to the topic list
$("#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>
This all works correctly by cloning the list item, setting up the click action, 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 list is undefined (or not a Jquery object), it throws an exception.
An empty jQuery object is declared as:
Docs for jQuery object creation: http://api.jquery.com/jQuery/
EDIT:
It sounds like you’re trying to eliminate the
if/elsestatement by extendinglistwhether or not it has any content.Is that right?
If so, try something like this:
or
(Assumes
listis starting out as an empty jQuery object.)EDIT:
Since you’re creating elements in a loop, you can always
push()then into a jQuery object.Try something like this:
(I edited from the original to only push the DOM element into the jQuery object.)
Should add the current item in the loop to your list.
You could eliminate the
find()calls in your code if you just cloned the children of#object_item_list_template:Now you have a clone of the
liitself. No need to do a find.