on the jQuery object that take a function. For example, we can make all the
links on a page with the class of popup open in a new window, like this:
jqueryprimer/popup.html
Line 1 varlinks= $("a.popup");
2 links.click(function(event){
3 varaddress= $(this).attr('href');
4 event.preventDefault();
5
});
window.open(address);
6
Inside our jQuery event handler, we can access the element we’re working
with by using the this keyword. On line 3, we pass this to the jQuery function
so we can call the attr() method on it to quickly retrieve the link’s destination
address.
We use the preventDefault() function to keep the original event from firing so it
doesn’t interfere with what we’re doing.
Binding Events
Some events don’t have jQuery shortcuts, so we can use the on() method to
handle those events. For example, when implementing the Drag and Drop
part of the HTML5 specification, we need to cancel out the ondragover event.
We use the on() like this:
jqueryprimer/events.html
target= $("#droparea")
target.on('dragover',function(event){
event.preventDefault();
returnfalse;
});
Notice that we drop the on prefix for the event we’re watching.
Binding Events at a Higher Level
Adding click events to individual elements can make the page render more
slowly and take up more resources than necessary. Instead of adding events
on individual items, we listen for events on the element containing the items:
jqueryprimer/events.html
Line 1 varlinks= $("#links");
2 links.click(function(event){
3 link= event.target;
4 varaddress= $(link).attr('href');
5 event.preventDefault();
6
});
window.open(address);
7
Appendix 2. jQuery Primer • 268
Download from Wow! eBook <www.wowebook.com> report erratum • discuss