译文:JavaScript框架比较–事件处理(五)
事件处理
每个JavaScript框架都实现跨浏览器的事件处理,鼓励你摆脱旧式的内联附加事件而使用精简的线性方法。看看清单6的jQuery例子,使用hover事件高亮显示div元素。 清单6:使用jQuery附加hover事件 $('#the-box').hover(function() { $(this).addClass('highlight'); }, function() { $(this).removeClass('highlight'); }); 清单7:使用jQuery附加click事件 $('#the-button').click(function() { alert('You pushed the button!'); }); 清单8:使用Prototype附加click事件 $('the-button').observe('click', function(e) { alert('You pushed the button!'); }); 清单9:使用Prototype附加悬停事件 $('the-box').observe('mouseover', function(e) { var el = Event.element(e); el.addClassName('highlight'); }); $('the-box').observe('mouseout', function(e) { var el = Event.element(e); el.removeClassName('highlight'); }); 通过该文章的一些教程,你可以看到函数以内联的方式创建,并不命名。这意味着它不能重复使用,Prototype的悬停示例也给了我们一个如何使用命名函数的机会。清单10说明了这个方法。 清单10:使用Prototype改进悬停事件 function toggleClass(e) { var el = Event.element(e); if(el.hasClassName('highlight')) row.removeClassName('highlight'); else row.addClassName('highlight'); } $('the-box').observe('mouseover', toggleClass); $('the-box').observe('mouseout', toggleClass); 转载地址:http://www.denisdeng.com/?p=720 原文地址:http://www.ibm.com/developerworks/web/library/wa-jsframeworks/index.html (编辑:PHP编程网 - 黄冈站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |