
为什么会出现上图这种情况
能通过property修改class 使attribute和property都变化
但是 通过property却只能修改value都property 无法修改attribute
再具体点说就是为什么
通过 i1.value ='...' 没有改变i1的html
但是通过 div1.classname='...' 改变的div1的html?
DOM元素含有的这两个东西,虽然完全不是一回事,但却又紧密联系在一体,不细细体会,还真不好分清。Property-属性,就像C#等高级语言可以.(dot)获取或者设置其值;Attribute-特性,每一个dom元素都有一个attributes属性来存放所有的attribute节点,通过getAttribute()和setAttribute()方法来进行获取和操作。
1
上例中div里面的id、name、class还有自定义的customtag都放到了attributes里面,attributes类似数组的容器,名字索引存放的是name=value的attribute的节点,上面的就是
[class="center",name="div1",id="test",customtag="divTest"]
需要获取和设置这些attribute,很简单
document.getElemmentById("test").getAttribute("customtag") //divTest
document.getElemmentById("test").setAttribute("data","11")
document.getElemmentById("test").removeAttribute("data")
Property就是一个属性,如果把DOM元素看成是一个普通的object对象,那么property就是以name=value形式存放在Object中的属性(C#中的类似),操作很简单
elem.gameid = 880; // 添加
console.log( elem.gameid ) // 获取
这两个东西有什么联系和区别呢?
首先,很多attribute节点有一个相应的property属性,如例子中的div元素的id和class既是attribute也有property,不管哪种方式都可以访问和修改,但是对于自定义的attribute节点,或者自定义property,两者就没有关系了,对于IE6-7来说,没有区分attribute和property。具体的讲解可以考attribute和property的区别,很详细。
虽然getAttribute和点号方法都能获取标准属性,但是他们对于某些属性,获取到的值存在差异性,比如href,src,value等
Test Link
var $ = function(id){return document.getElementById(id);}; alert($('link').getAttribute('href'));//# alert($('link').href);//fullpath/file.html# alert($('image').getAttribute('src'))//img.png alert($('image').src)//fullpath/img.png alert($('ipt').getAttribute('value'))//enter text alert($('ipt').value)//enter text $('ipt').value = 5; alert($('ipt').getAttribute('value'))//enter text alert($('ipt').value)//5
你好 从几片上看没有看出什么问题来,只是看到获取的值发生了变化。所以我猜想是不是你改变值后再获取才这样的
attribute是html中某个标记的尖括号里附加的特性(<div name="aaa">,则name就是一个attrbiute)
property是js里的属性,比如对象或者json里的字段。
var obj;
obj.name = "aaa"; //这是属性,是js语法的一部分,不是html
因为html的特性不是js语法的一部分,所以不能直接赋值,只能通过函数(比如setAttribute或者jq的attr设置)
https://www.cnblogs.com/elcarim5efil/p/4698980.html
我想这篇文章可能会对你有所帮助。