为什么称属性和属性为“表亲戚”呢& # 63;因为他们既有共同处,也有不同点。
属性是dom元素在文档中作为html标签拥有的属性;
属性是dom元素在js中作为对象拥有的属性。
<强>从定义上可以看出:强>
-
<李>对于html的标准属性来说,属性和属性是同步的,是会自动更新的李>
<李>但是对于自定义的属性来说,他们是不同步的。(自定义属性不会自动添加到属性)李>
<李>属性的值可以改变,属性的值不能改变李>
<强> 1,分别打印两个值强>
打印属性属性
//html & lt; div类=" divClass " id=" divId祝辞& lt;/div>//js 窗口。onload=function () { var divId=. getelementbyid (“divId”); console.log (divId.attributes); }
console.log (divId.attributes [0]);//打印类=" divClass " console.log (divId.attributes.class)//打印类=癲ivClass” console.log (divId.getAttribute(类))//打印divClass console.log (divId.getAttribute (id))//打印divId
发现上面两组值是相等的。
虽然都可以取的值,但《js高级程序设计》中提到,为了方便操作,建议大家用setAttribute()和getAttribute()来操作即可。
<>强打印地产强>
html自带的dom属性会自动转换成属性,但是自定义的属性没有这个的权利”
直接把div标签当作对象,用”。“输出即是产权属性
& lt; div类=" divClass " id=" divId " addUserDefine=皕idingyi祝辞& lt;/div> console.log (divId.class);//打印divClass console.log (divId.addUserDefine)//打印未定义的
打开元素的属性可以看的到,dom存在的属性,财产同样继承了,而addUserDefine却没有出现在房地产中
属性:
var obj={}; Object.defineProperty (obj,“名字”,{ 价值:“财产” }) console.log (obj.name)//打印地产
如果我们修改了属性的值
//html & lt;输入值=" https://www.yisu.com/zixun/initValue " id=癷pt”/比;//js 窗口。onload=function () { var ipt=. getelementbyid (ipt); ipt。值=' https://www.yisu.com/zixun/changeValue ' console.log (ipt.value); console.log (ipt.getAttribute(“价值”); }
猜一下结果& # 63;& # 63;
答案是:
console.log (ipt.value);//changeValue console.log (ipt.getAttribute(“价值”);//initValue
我们再来看看输入的值
//html & lt;输入值=" https://www.yisu.com/zixun/initValue " id=癷pt”/比;//js 窗口。onload=function () { var ipt=. getelementbyid (ipt); ipt.setAttribute(“价值”、“changeValue”) console.log (ipt.value); console.log (ipt.getAttribute(“价值”); }
输出:
console.log (ipt.value);//changeValue console.log (ipt.getAttribute(“价值”);//changeValue
总结如下:
-
<李>属性比属性“霸道”,估计是“表哥”李>
<李>属性和属性两者是属于单方面通信,即:李>
1。财产能够从属性中得到同步;
2。属性不会同步财产上的值;
<强>再啰嗦一句:强>
对属性财产可以赋任何类型的值,而对特性属性只能赋值字符串!