javascript
JavaScript中setAttribute用法
?
我們經常需要在JavaScript中給Element動態添加各種屬性,這可以通過使用setAttribute()來實現,這就涉及到了瀏覽器的兼容性問題。
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控件具有bordercss樣式屬性
注意:class屬性在W3C DOM中扮演著很重要的角色,但由于瀏覽器差異性仍然存在。
使用setAttribute(class, vName)語句動態設置Element的class屬性在firefox中是行的通的,但在IE中卻不行。因為使用IE內核的瀏覽器不認識class,要改用className;
同樣,firefox 也不認識className。所以常用的方法是二者兼備:
element.setAttribute(class, value);? //for firefox
element.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).οnclick= function () { alert(This is a test!); }
由此延伸的問題:
一個input的text,當將html賦值為某個div的innerHTML時,遇到一個現象,當在firefox下時(IE下不存在此問題), 賦值后的innerHTML里不含有value,即當你在文本框輸入內容后,你想將賦值給div時,只會得到,這里總是會將value清除.
這時,setAttribute起作用了,在input內加上:οnkeyup=this.setAttribute('value',this.value),即動態的將input控件加上value值,這時再將文本框賦值給div,value將不會被清空.
?
出處:http://webcenter.hit.edu.cn/articles/2009/05-16/05070500.htm
轉載于:https://www.cnblogs.com/furenjian/articles/3242945.html
總結
以上是生活随笔為你收集整理的JavaScript中setAttribute用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sqlserver compact sd
- 下一篇: Android UI开发第二十七篇——实