一个同事无意中发现的问题,jQuery版本1.4.4
测试代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> <script type="text/javascript" src="jquery-1.4.4.js"></script> <script language="JavaScript"> <!-- $(function (){ //这里添加一个属性aaa,值为true(不是字符串'true',字符串没有问题) $('#ttt').attr('aaa',true); alert(typeof $('#ttt').attr('aaa')); //这里再次修改属性aaa,值为true(不是字符串'true',字符串没有问题) $('#ttt').attr('aaa',true); alert(typeof $('#ttt').attr('aaa')); }); //--> </script> </head> <body> <textarea id="ttt" rows="" cols=""></textarea> </body> </html>
在IE8中运行,两次alert的结果不同,why...
第一次是String,第二次是boolean,百思不得其解...
火狐,google都是String
最后用IE8调试jQuery源码:
if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; }
第二次是在是在这里返回的,有些不理解.
在1.6.1中,他重写了这块的代码,没有出现这个怪异的问题,
if ( !hooks ) { // Use boolHook for boolean attributes if ( rboolean.test( name ) && (typeof value === "boolean" || value === undefined || value.toLowerCase() === name.toLowerCase()) ) { hooks = boolHook; // Use formHook for forms and if the name contains certain characters } else if ( formHook && (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) { hooks = formHook; } }
难道这是它1.4.4的一个bug...
大家可以讨论这个问题...
你的调试肯定有问题……
第一次set的时候,因为elem下没有aaa这个property,因此判定对于该元素,aaa这个attribute并没有对应的property,所以走的是elem.setAttribute('aaa', true),根据DOM标准,setAttribute将value转为string,拿出来的是'true'
第二次set的时候,由于IE6-8不区分attribute和property,且由于前面设置了一次aaa这个属性,导致判断elem下有了aaa这个property,所以直接使用了elem['aaa'] = true来设置,property没有自动转换为string的机制,所以拿出来的是true
对于其他浏览器,第一次用的是setAttribute,不会影响property的获取,第二次依旧判断没有aaa这个property,依旧用setAttribute
只是IE的BUG而已,也不能全说是jquery的错