javascript property和attribute的区别和同步问题

js Dom对象property与attribute区别
  1. property和attribute的翻译都是属性的意思,但在《js高级程序设计中》将property翻译为属性,将attribute翻译为特性
  2. attribute:html中的预定义特性和自定义特性
    下面代码中id为html的预定义特性, abc是我们的自定义特性
<p id="title" abc="edf"></p>
  1. property: js原生对象的直接属性
    • 每一个预定义的attribute都会有一个property与之对应
<p id="title" abc="edf"></p>

//js
var pDom = document.getElementById("title");
console.log(pDom.id) //title
console.log(pDom.abc) //undefine
向上面代码显示的那样, html的预定义属性在Dom对象中都有一个property与之对应,
而自定义属性没有,要获取自定义属性的值需要使用dom对象的Attribute属性
  1. Dom的Attribute属性
    • Dom对象的Attribute属性记录了一个html标签的所有attribute,包括预定义的和自定义的, 我们可以通过getAttribute方法来获取标签中的attribute
    • 我们暂且可以这样理解,getAttribute获取的是html标签上的特性(感觉称呼为属性比较合适一点,但为了区分,还是称呼为特性吧)
    console.log(pDom.getAttribute("id"))//title,id为预定义特性
    console.log(pDom.getAttribute("abc"))//edf,自定义特性
有getAttribute方法自然也有setAttribute方法,
使用setAttribute设置html标签的预定义属性是,Dom对象的property会收到一定的影响
    pDom.setAttribute("id", "aaa");
    console.log(pDom.getAttribute("id"));//aaa
不过setAttribute方法存在是属性与特性同步的问题

4. setAttribute中属性与同步问题
* 在html的标签的预定义属性(attribute)中,在Dom对象都有property与之对应,Dom对象的attribute属性也有相应的属性与之对应(这就是为什么我们能用getAttribute来获取html的预定义attribute)
* setAttribute能改变Dom对象中与attribute中向对应的值,向对应的property也会受到一定的影响,但有特性与属性同步的问题

非布尔值类型的属性与特性的同步问题

先上代码

<input id="text" name="aaa" />

var dom = document.getElementById("test");
console.log(dom.name) //aaa
console.log(dom.getAttribute("name")) //aaa
dom.name="bbb";
console.log(dom.getAttribute("name")) //bbb
dom.setAttribute("name", "ccc")
console.log(dom.name) //ccc

有上面的代码可知,对于非布尔值类型的,属性和特性无论什么情况下都会同步

布尔值类型的属性与特性
<input type="checkbox"   name="qhf"/>


var qhf = document.querySelector("input[type=checkbox]");
//debugger
console.log(qhf.checked)//false
qhf.setAttribute("checked","qhf1")
qhf.setAttribute("checked","qhf2")
qhf.setAttribute("checked","qhf3")
console.log(qhf.checked); //true
qhf.checked="qhf4"; //因为checked属性是布尔值属性,所以这行代码会将checked值变为true
qhf.checked="qhf5";
qhf.checked="qhf6";
qhf.checked=false;
console.log(qhf.getAttribute("checked"));
qhf.setAttribute("checked","qhf7")
qhf.setAttribute("checked","qhf8")
qhf.setAttribute("checked","qhf9")
console.log(qhf.checked) //false

对于布尔值属性
1.改变 property时,不会同步attribute
2.在没有动过property时
attribute会同步property
一旦动过property
attribute不会同步propertyr

猜你喜欢

转载自blog.csdn.net/qq_36297981/article/details/80234493