读jQuery之九(一些瑕疵)
jQuery1.6.1 发布有一段时间了,发现一些冗余代码,列出如下
1,bind 方法,最后一个参数fn是多余的
// Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; }
2,注释
// Add which for click: 1 === left; 2 === middle; 3 === right
应修改为
// Add which for mousedown/mouseup : 1 === left; 2 === middle; 3 === right
3,data方法,定义了局部变量internalKey,但后续代码仍然沿用jQuery.expando。
var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
4,jQuery.event.add方法,arguments改为e,apply改为call 更好一些。因为只会传一个参数:事件对象。
elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; };
5,基于 “勿重复检测浏览器” 原则,jQuery.event.add 以下代码
if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); }
应该使用以下来替换
jQuery.addEvent = document.addEventListener ? function( elem, type, handle ) { if ( elem.addEventListener ) { elem.addEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.attactEvent ) { elem.attactEvent( "on" + type, handle ); } };
事实上,jQuery中已经有了jQuery.removeEvent,却不知为何没有jQuery.addEvent。
jQuery1.6.2
6,attr方法获取style属性时IE6/7/8与IE9/Firefox/Safar/Chrome/Opera值不一致。IE6/7/8中少了分号。如下
<div style="color:red;">test</div> <script type="text/javascript"> alert($('div').attr('style')); </script>
持续更新...