js中的setattribute是什么?有什么作用?一起來(lái)看看小編今天的分享吧。
setattribute的作用就是增加一個(gè)指定名稱和值的新屬性,或者把一個(gè)現(xiàn)有的屬性設(shè)定為指定的值。在JavaScript中,如果要給Element動(dòng)態(tài)添加各種屬性,就需要通過(guò)使用setAttribute()來(lái)實(shí)現(xiàn)。
下面是具體示例:
1、樣式問(wèn)題
setAttribute("class", value)中class是指改變"class"這個(gè)屬性,所以要帶引號(hào)。
var input = document.createElement("input"); input.setAttribute("type", "text"); input.setAttribute("name", "q"); input.setAttribute("class",bordercss);
輸出時(shí):,即,input控件具有bordercss樣式屬性
注意:class屬性在W3C DOM中扮演著很重要的角色,但由于瀏覽器差異性仍然存在。
使用setAttribute("class", vName)語(yǔ)句動(dòng)態(tài)設(shè)置Element的class屬性在firefox中是行的通的,但在IE中卻不行。因?yàn)槭褂肐E內(nèi)核的瀏覽器不認(rèn)識(shí)"class",要改用"className";
同樣,firefox 也不認(rèn)識(shí)"className"。所以常用的方法是二者兼?zhèn)洌?/p>
element.setAttribute("class", value); //for firefox element.setAttribute("className", value); //for IE
2、方法屬性等問(wèn)題
var bar = document.getElementById("testbt"); bar.setAttribute("onclick", "javascript:alert('This is a test!');");
這里利用setAttribute指定e的onclick屬性,但是IE不支持,IE并不是不支持setAttribute這個(gè)函數(shù),而是不支持用setAttribute設(shè)置某些屬性,例如對(duì)象屬性、集合屬性、事件屬性,也就是說(shuō)用setAttribute設(shè)置style和onclick這些屬性在IE中是行不通的。
為達(dá)到兼容各種瀏覽器的效果,可以用點(diǎn)符號(hào)法來(lái)設(shè)置Element的對(duì)象屬性、集合屬性和事件屬性。
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!"); }
以上就是小編今天的分享了希望可以幫助到大家。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com