2010-07-21 54 views

回答

3

它會在任何情況下返回值。

<div class="sOmEcLaSs">content</div> 

alert($('div').attr('class')​​​​);​​​​ // will alert sOmEcLaSs 

如果你想轉換爲小寫,您可以使用.toLowerCase()

alert($('div').attr('class').toLowerCase());​​​​ // will alert someclass 

代碼jQuery的attr return語句(沒有嘶嘶聲):

http://github.com/jquery/jquery/blob/1.4.2/src/attributes.js#L308

http://github.com/jquery/jquery/blob/1.4.2/src/attributes.js#L325

2

沒有因爲.attr調用JavaScript .getAttribute方法無任何參數。如您在代碼下面看到的那樣。

getAttribute默認爲0,這是不區分大小寫的,因此它返回的結果就是它找到的內容。

 ATTR: function(elem, match){ 
      var name = match[1], 
       result = Expr.attrHandle[ name ] ? 
        Expr.attrHandle[ name ](elem) : 
        elem[ name ] != null ? 
         elem[ name ] : 
         elem.getAttribute(name), 
       value = result + "", 
       type = match[2], 
       check = match[4]; 

      return result == null ? 
       type === "!=" : 
       type === "=" ? 
       value === check : 
       type === "*=" ? 
       value.indexOf(check) >= 0 : 
       type === "~=" ? 
       (" " + value + " ").indexOf(check) >= 0 : 
       !check ? 
       value && result !== false : 
       type === "!=" ? 
       value !== check : 
       type === "^=" ? 
       value.indexOf(check) === 0 : 
       type === "$=" ? 
       value.substr(value.length - check.length) === check : 
       type === "|=" ? 
       value === check || value.substr(0, check.length + 1) === check + "-" : 
       false; 
     }, 
0

jQuery不能依賴於區分大小寫的屬性搜索,仍然是跨瀏覽器瀏覽器兼容。在舊的IE DOM中,我記得所有的標籤和屬性都以大寫形式存儲和返回;所以標籤<div id="mydiv">在內部呈現爲<DIV ID=mydiv>。所以在Netscape或Firefox中,屬性名稱將是id,在IE中它將是ID。但即使使用動態創建的元素(這些元素與所需的情況一起存儲),在IE中也存在不一致。例如,IE6和IE8的行爲與getAttribute()完全不同。比較:

<div></div> 

var myDiv = document.getElementsByTagName('div')[0]; 
myDiv.setAttribute('id','id1'); 
myDiv.setAttribute('ID','id2'); 
console.log(x.getAttribute('ID')); // IE6, return "id1", IE8, returns "id2" 
console.log(x.getAttribute('ID',true)); // IE6, return "id2", returns "id2"