From this HTML. you want to call functions rather than go to links.
Great Web resources
- Opera Web Standards Curriculum
- Sitepoint
- A List Apart
- YUI Blog
- Blame it on the voices
- Oddly specific
Author's first example code:
// Classic event handling example (function(){ var resources = document.getElementById('resources'); var links = resources.getElementsByTagName('a'); var all = links.length; for(var i=0;i<all;i++){ // Attach a listener to each link links[i].addEventListener('click',handler,false); }; function handler(e){ var x = e.target; // Get the link that was clicked alert(x); e.preventDefault(); }; })();
Author's second example code:
(function(){ var resources = document.getElementById('resources'); resources.addEventListener('click',handler,false); function handler(e){ var x = e.target; // get the link that was clicked if(x.nodeName.toLowerCase() === 'a'){ alert('Event delegation:' + x); e.preventDefault(); } }; })();
My take, assuming jQuery:
$( function() { $( '#resources li a' ).click( function() { alert( 'Event delegation: ' + $(this).attr('href') ) ; return false ; } ) ; } ) ;
Unless I miss a trick, it works the same and uses far fewer lines.
No comments:
Post a Comment