From this HTML. you want to call functions rather than go to links.
- <h2>Great Web resources</h2><ul id="resources"> <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>
- <li><a href="http://sitepoint.com">Sitepoint</a></li>
- <li><a href="http://alistapart.com">A List Apart</a></li>
- <li><a href="http://yuiblog.com">YUI Blog</a></li>
- <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>
- <li><a href="http://oddlyspecific.com">Oddly specific</a></li>
- </ul>
- 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