js 中设置或获取自定义属性的方法setAttribute getAttribute attributes

1. setAttribute(attributename,attributename) 方法添加指定的属性,并为其赋指定的值。

属性可以是自定义的属性,如果这个指定的属性已存在,则仅设置/更改值

2. getAttribute(attributename);获取某个属性的值;返回值为string类型

注:attributename,value都是字符串类型

3. attributes;返回元素属性的 NamedNodeMap(返回所有属性的集合,如果通过该方法获取属性,obj.attributes['attr'])

注:Internet Explorer 8 以及更早的版本中,attributes 属性将返回元素所有可能的属性的集合,即会返回所有隐藏的属性

attributes中的属性可以通过数组的方式来获取对应的属性值

 

<input type="text" id="txtMsg" myAttr="abc" />
var myAttr = document.getElementById("txtMsg").attributes["myAttr"].value;     //通过attributes属性
var myAttr = document.getElementById("txtMsg").getAttribute("myAttr");       //使用getAttribute方法
document.getElementById("txtMsg").setAttribute("myAttr", "newValue");          //通过setAttribute方法设置属性的值
var myAttr = document.getElementById("txtMsg").attributes["myAttr"].value;   //通过attributes属性
var myAttr = document.getElementById("txtMsg").getAttribute("myAttr");       //使用getAttribute方法

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值