</div>
1、js中设置自定义属性。
例如:$(".div-info").attr("testAttr3","houhou")
结果:给div设置了新的自定义属性testAttr3,值为houhou
<div class="div-info" testAttr="myAttr" testAttr2="haha" testAttr3="houhou">
</div>
2、js中获取自定义属性值。
例如:$(".div-info").attr("testAttr")
结果:取到testAttr的值为:myAttr
3、js中修改自定义属性值。
例如:$(".div-info").attr("testAttr","newAttr")
结果:将testAttr的值修改为newAttr
<div class="div-info" testAttr="newAttr" testAttr2="haha">
</div>
4、js中删除自定义属性
来自参考!
var source = '<div style="a:a b:b c:c" width="10%" height="dd"></div>'// 删除width属性及值。
console.log(source.replace(/width=".*?"/,''))
//删除style属性中的键值对b和c
console.log(source.replace(/(style=")(.*?)(")/,function(m,g1,g2,g3){
return g1 + g2.replace(/\s?(.*?):(.*?)/g,function(m,g1,g2){
// 删除b属性和c属性 要改成其他属性可以在这里控制
if(/^(b|c)$/.test(g1))
return ''
return m
}) + g3
}))
删除对象,直接使用delete就可以了。比如:delete document.getElementById('div')
删除一个属性的过程也很简单,就是将其置为undefined:
user.name=undefined
user.alert=undefined
这样就删除了name属性和alert方法。在之后的代码中,这些属性变的不可用。
在添加、修改或者删除属性时,和引用属性相同,也可以采用方括号([])语法:
user[“name”]=”tom”
使用这种方式还有一个额外的特点,就是可以使用非标识符字符串作为属性名称,例如
标识符中不允许以数字开头或者出现空格,但在方括号([])语法中却可以使用:
user[“my name”]=”tom”
需要注意,在使用这种非标识符作为名称的属性时,仍然要用方括号语法来引用:
alert(user[“my name”])
而不能写为:
alert(user.my name)