本文實例分析了javascript中setAttribute兼容性用法。分享給大家供大家參考,具體如下:
1:常規屬性建議使用 node.XXXX。
2:自定義屬性建議使用node.getAttribute("XXXX")。
3:當獲取的目標是JS里的關鍵字時建議使用node.getAttribute("XXX"),如label中的for。
4:當獲取的目標是保留字,如:class,請使用className代替。
setAttribute(string name, string value):增加一個指定名稱和值的新屬性,或者把一個現有的屬性設定為指定的值。
1、樣式問題
setAttribute("class", value)中class是指改變"class"這個屬性,所以要帶引號。
vName代表對樣式賦值。
例如:
代碼如下:
var input = document.createElement("input");input.setAttribute("type", "text");input.setAttribute("name", "q");input.setAttribute("class",bordercss);
輸出時:<input type="text" name="q" class="bordercss">,即,input控件具有bordercss樣式屬性
注意:class屬性在W3C DOM中扮演著很重要的角色,但由于瀏覽器差異性仍然存在。
使用setAttribute("class", vName)語句動態設置Element的class屬性在firefox中是行的通的,但在IE中卻不行。因為使用IE內核的瀏覽器不認識"class",要改用"className";
同樣,firefox 也不認識"className"。所以常用的方法是二者兼備:
代碼如下:
element.setAttribute("class", value); //for firefoxelement.setAttribute("className", value); //for IE
2、方法屬性等問題
例如:
代碼如下:
var bar = document.getElementById("testbt");bar.setAttribute("onclick", "javascript:alert('This is a test!');");
這里利用setAttribute指定e的onclick屬性,簡單,很好理解。
但是IE不支持,IE并不是不支持setAttribute這個函數,而是不支持用setAttribute設置某些屬性,例如對象屬性、集合屬性、事件屬性,也就是說用setAttribute設置style和onclick這些屬性在IE中是行不通的。
為達到兼容各種瀏覽器的效果,可以用點符號法來設置Element的對象屬性、集合屬性和事件屬性。
代碼如下:
document.getElementById("testbt").className = "bordercss";document.getElementById("testbt").style.cssText = "color: #00f;";document.getElementById("testbt").style.color = "#00f";document.getElementById("testbt").onclick= function () { alert("This is a test!"); }
示例:
<!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><script type="text/javascript">var el = document.getElementById("idHeader");alert(el.getAttribute("id"));alert(el.id);// IE Firfox->idHeaderalert(el.getAttribute("class"));//IE6,IE7 -> null IE8,IE9,Firefox ->class-headeralert(el.class);//IE6,IE7,IE8->報錯 IE9,Firefox->undefinedalert(el.getAttribute("className"));//IE6,IE7->class-header ; IE8,IE9,Firefox -> undefinedalert(el.className);//All -> class-headervar elfor = document.getElementById("forUserName");alert(elfor.getAttribute("for"));//IE6,IE7->undefined IE8,9,Firefox->forUseNamealert(elfor.for )//IE6,IE7報錯,其它為undefinedalert(elfor.title)//全部輸出kingwellalert(elfor.status);//IE6-8 -> 1 IE9,Firefox->undefinedalert(elfor.getAttribute("status"))//全部輸出 1</script></body></html>
更多關于JavaScript相關內容可查看本站專題:《JavaScript常用函數技巧匯總》、《javascript面向對象入門教程》、《JavaScript中json操作技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答