js中元素屬性的擷取

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   使用   ar   java   for   

方式一: element.attribute

方式二:element.getAttribute("attribute");

方式三:element.className;

一:前言

因為以前看過一篇張鑫旭的部落格,記得裡邊有提到getAttribute的相容性問題,但是具體的又想不起來,就自己先測試一下,但是的但是,巧合就這麼簡單,小女子我使用的是元素的class屬性,然後不知覺地就掉入大坑了。

測試的結果是ele.getAttribute("class")在IE7(含)以下的版本中彈出的是null,以為是個相容問題,在網上找了一天的解決方案,最後是在沒有辦法,就又將張鑫旭的那篇文章看了一遍,看到最後,內傷無數啊,裡邊提到的getAttribute跟DOM中的這個完全不是一回事兒的,當時沒看懂,想著以後學到DOM的時候再看,結果的結果……哦啊……算了,不說了

二:以上三種方式的區別

都在代碼中,自己看吧……

HTML:

<!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><title>kingwell</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><body><div id="idHeader" class="class-header" title="kingwell" status="1"></div><label id="forUserName" for="userName" title="kingwell" status="1"></label></body></html>

javascript:

var el = document.getElementById("idHeader");    alert(el.getAttribute("id"));    alert(el.id);    //IE Firfox->idHeader    alert(el.getAttribute("class"));    //IE6,IE7 -> null IE8,IE9,Firefox ->class-header    alert(el.class);    //IE6,IE7,IE8->報錯 IE9,Firefox->undefined    alert(el.getAttribute("className"));    //IE6,IE7->class-header ; IE8,IE9,Firefox -> null    alert(el.className);    //All -> class-header    var elfor = document.getElementById("forUserName");    alert(elfor.getAttribute("for"));    //IE6,IE7->undefined IE8,9,Firefox->forUseName    alert(elfor.for )    //IE6,IE7報錯,其它為undefined    alert(elfor.title)    //全部輸出kingwell    alert(elfor.status);    //IE6-8 -> 1 IE9,Firefox->undefined    alert(elfor.getAttribute("status"))    //全部輸出 1        /*總結:    1:常規屬性建議使用 node.XXXX。    2:自訂屬性建議使用node.getAttribute("XXXX")。    3:當擷取的目標是JS裡的關鍵字時建議使用node.getAttribute("XXX"),如label中的for。    4:當擷取的目標是保留字,如:class,請使用className代替。    */

這個總結也非本人成果,但是中間有個小小的錯誤,已改;

為表達對原著者的尊重,下邊是連結:

http://kingwell-leng.iteye.com/blog/1663553

 

js中元素屬性的擷取

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.