Web Development with jQuery®

(Elliott) #1

(^198) ❘ CHAPTER 7 AJAX
$(this).next().toggle();
if ($(this).attr('src').indexOf('down') != -1)
{
arrow = 'tree/right.png';
}
$(this).attr('src', arrow);
}
}
);
}
);
All put together, the preceding code looks like Figure 7-4 when it is tested in a browser.


FIGURE 7-4


In the preceding script, a click event is attached to each <img> element in the HTML document.
When the user clicks the <img> element, which is a gray arrow, the script fi rst checks to see whether
the folder’s contents have already been requested, which is done by checking to see if the <img>
element’s next sibling, the <div> element with class name folderTreeBranchWrapper, has a child <ul>
element. Whether that <ul> element exists is determined by the following expression:

if (!$(this).next().children('ul').length)
{

The next() method traverses the selection from the <img> to the <div> element, and the children()
method looks at the children of the <div> method. Then the length property determines how many
children <ul> elements exist. If there is a <ul> element, that means the folder’s contents have already
been requested from the server and loaded into the document. If there is not a <ul> element, then the
folder’s contents are requests from the server.

Loading directly in the document is done based on a selection. In this script, you select the <div>
element with the class name folderTreeBranchWrapper, which is done with the call to $(this)

http://www.it-ebooks.info

Free download pdf