Java Reference
In-Depth Information
This code results in the same outcome, and it's a little bit easier to understand. However, if you wanted
to save even more lines, you could do something like the following code:
function document_ready()
{
$(document.body).append($(document.createElement(“a”))
.attr(“id”, “myLink”).attr(“href”, “http://jquery.com”)
.attr(“title”, “jQuery's Website”)
.text(“Click here to go to jQuery's website.”));
}
This code certainly is smaller and more compact, and it is the type of code you'd see if you looked at lots
of the jQuery-based code out on the Internet (and it's the type of code you'd see your authors write).
You do lose some readability, however. The important thing is to code in a manner that you feel comfort-
able with. Method chaining can get a little confusing if several methods are chained together. For this
purpose, the remainder of the code examples will put each method call on a separate line.
Removing Elements
Removing elements from the DOM is also much easier with jQuery than with the traditional DOM
methods. Using the latter, you have to fi nd at least two elements in the DOM tree: the element you want
to remove and its parent element. With jQuery, you only need to fi nd the element you want to remove
and call the remove() method, like this:
$(“#myLink”).remove();
This code fi nds the <a/> element you created in the previous code example and removes it from the
DOM. You can also remove all of a parent's child nodes by calling the empty() method.
$(document.body).empty();
This code empties the <body/> element, thus removing all content from the page.
Most DOM changes you'll make are in response to something the user did, whether it be moving their
mouse over a particular element or clicking somewhere on the page. So naturally, you'll have to handle
events at some point.
The jQuery Event Model and Handling Events
All jQuery objects expose a method called bind(), which you use to assign event handlers to specifi c
events.
function myButton_click(event)
{
alert(“You clicked me!”);
}
$(“#myButton”).bind(“click”, myButton_click);
Search WWH ::




Custom Search