HTML and CSS Reference
In-Depth Information
the closing tag for the elements that match the selector. In this case, I put the value in the
text field, which I obtain using the val() method that you've already seen, inside an
opening and closing <li> tag, and pass that to the append() method. I also remove the
content from the text field because it has been appended to the list. Figure 16.13 shows
the list once a few elements have been added.
FIGURE 16.13
A page that allows
you to add and
remove content
Finally, I allow users to remove items from the list by clicking them. There's one trick
here. As you've seen, to do so I'll need to use the click handler for the <li> elements in
the list. In this case, there's a catch. When the page loads and the document.ready event
for the page initially fires, there are no elements in the list to bind events to. Fortunately,
jQuery provides a way to set up an event handler so that it's automatically bound to
newly created elements on the page. Here's the code:
$(“#editable li”).live('click', function () {
As you can see, the event binding is slightly different here. Instead of using the click()
method, I've used the live() method. This indicates that I want to monitor changes to
the page and perform the event binding that follows any time an element matching the
selector is added. The first argument is the name of the event to bind—it's the name of
the event to be bound, placed in quotation marks. The second is the event handler as it
would normally be written. The live() method is one of the most powerful features of
jQuery because it enables you to automatically treat dynamically generated content the
same way you'd treat content that's on the page at the time that it loads.
Here's the full source for the page:
<!DOCTYPE html>
Search WWH ::

Custom Search