广州明生堂生物科技有限公司


JavaScript中setAttribute用法介绍

网络编程 JavaScript中setAttribute用法介绍 06-22
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 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").onclick= function () { alert("This is a test!"); }

通过一段代码简单说js中的this的使用
今天有朋友说遇到如下代码,让我帮解释原因varname="TheWindow";varobject={name:"MyObject",getNameFunc:function(){returnfunction(){returnthis.name;};}};alert(object.getNameFunc()());

a标签的href和onclick 的事件的区别介绍
1、onclick事件先执行,如果onclick事件返回一个false值则href不再执行。2、href=#默认页面到锚点#top所以页面有滚动条时会跳到最上面。最好的解决办法是hre

js中widow.open()方法使用详解
一、window.open()支持环境:JavaScript1.0+/JScript1.0+/Nav2+/IE3+/Opera3+二、基本语法:window.open(pageURL,name,parameters)其中:pageURL为子窗口路径name为子窗口句柄paramete


编辑:广州明生堂生物科技有限公司

标签:属性,事件,不支持,样式,浏览器