Javascript相容性之——getAttribute(),setAttribute()(擷取設定屬性)

來源:互聯網
上載者:User

做前端的,總是要跟相容性打交道,CSS相容性,JS相容性,這裡我總結了一些getAttribute(),setAttribute()在不同瀏覽器下相容性以及如何解決這些問題:

 1     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   2     <html xmlns="http://www.w3.org/1999/xhtml">   3     <head>   4     <title>kingwell</title>   5     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   6     <body>   7        8     <div id="idHeader" class="class-header" title="kingwell" status="1"></div>   9     <label id="forUserName" for="userName" title="kingwell" status="1"></label>  10       11     </body>  12     </html>  

 

 1     var el = document.getElementById("idHeader");   2     alert(el.getAttribute("id"));   3     alert(el.id);   4     IE Firfox->idHeader   5        6     alert(el.getAttribute("class"));   7     //IE6,IE7 -> null IE8,IE9,Firefox ->class-header   8        9     alert(el.class);  10     //IE6,IE7,IE8->報錯 IE9,Firefox->undefined  11     alert(el.getAttribute("className"));  12     //IE6,IE7->class-header ; IE8,IE9,Firefox -> undefined  13       14     alert(el.className);  15     //All -> class-header  16       17       18     var elfor = document.getElementById("forUserName");  19     alert(elfor.getAttribute("for"));  20     //IE6,IE7->undefined IE8,9,Firefox->forUseName  21       22     alert(elfor.for )  23     //IE6,IE7報錯,其它為undefined  24     alert(elfor.title)  25     //全部輸出kingwell  26     alert(elfor.status);  27     //IE6-8 -> 1 IE9,Firefox->undefined  28       29     alert(elfor.getAttribute("status"))  30     //全部輸出 1   

    /*總結:
    1:常規屬性建議使用 node.XXXX。
    2:自訂屬性建議使用node.getAttribute("XXXX")。
    3:當擷取的目標是JS裡的關鍵字時建議使用node.getAttribute("XXX"),如label中的for。
    4:當擷取的目標是保留字,如:class,請使用className代替。
    */

 

這裡是分析的是getAttribute(),setAttribute()同理。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.