HTML中Attribute和JavaScript中property区别

来源:互联网 发布:mac系统无guid分区重装 编辑:程序博客网 时间:2024/04/25 06:18

Attribute是HTML标签中定义的属性

<div id="div" class="class" lang="ds" dir="ltr" title="title" userDefi="userDefi"></div>

例如上面定义的id,class,lang,dir,title,userDefi都是Attribute,都可以通过ele.getAttribute('id')这样获取其值。

Property是JavaScript为元素对象定义的属性

 var ele = document.getElementById('div');    ele.anotherProp = 'anotherP';

例如上面为ele定义的anotherProp.

共同拥有的属性

虽然AttributeProperty定义的属性分别在不同层面上,但是有以下几个属性是共享的:

id
class
lang
dir
title

<div id="div" class="class" lang="ds" dir="ltr" title="title" userDefi="userDefi"></div>    var ele = document.getElementById('div');    ele.anotherProp = 'anotherP';    ele.id = 'anotherId';    console.log(ele.getAttribute('id'));//div    console.log(ele.getAttribute('class'));//class    console.log(ele.getAttribute('lang'));//ds    console.log(ele.getAttribute('dir'));//ltr    console.log(ele.getAttribute('title'));//title    console.log('==============')    console.log(ele.id);//div    console.log(ele.className);//class    console.log(ele.lang);//ds    console.log(ele.dir);//ltr    console.log(ele.title);//title    console.log('==============')    console.log(ele.anotherProp);//anotherP    console.log(ele.getAttribute('anotherProp'));//null    console.log(ele.getAttribute('userDefi'));//userDefi    console.log(ele.userDefi);//undefined    ele.id = 'anotherId';    页面HTML标签同步显示id为anotherId

在页面改变input框的输入值并不会影响inputvalue

<input type="text" value="start" id="input"><input type="button" value="changevalue" id="btn"> btn.onclick = function () {     input.value = 123;     console.log(input.value);/123     console.log(input.getAttribute('value'));//start };