JS中attr和prop属性的区别

JavaScript012

JS中attr和prop属性的区别,第1张

JS中attr和prop属性的区别如下:

1、attr是attribute的缩写,是一个特性节点,每个DOM元素都有一个对应的attributes属性来存放所有的attribute节点,attributes是一个类数组的容器,说得准确点就是NameNodeMap,总之就是一个类似数组但又和数组不太一样的容器。attributes的每个数字索引以名值对(name=”value”)的形式存放了一个attribute节点。

<div class="box" id="box" gameid="880">hello</div>

上面的div元素的HTML代码中有class、id还有自定义的gameid,这些特性都存放在attributes中,类似下面的形式:

[ class="box", id="box", gameid="880" ]

可以这样来访问attribute节点:

var elem = document.getElementById( 'box' )

console.log( elem.attributes[0].name )// class

console.log( elem.attributes[0].value )// box

2、与之对应的property属性,比较特殊的是一些值为Boolean类型的property,如一些表单元素:

<input type="radio" checked="checked" id="raido">

var radio = document.getElementById( 'radio' )

console.log( radio.getAttribute('checked') )// checked

console.log( radio.checked )// true

对于这些特殊的attribute节点,只有存在该节点,对应的property的值就为true,如:

<input type="radio" checked="anything" id="raido">

var radio = document.getElementById( 'radio' )

console.log( radio.getAttribute('checked') )// anything

console.log( radio.checked )// true

3、了更好的区分attribute和property,基本可以总结为attribute节点都是在HTML代码中可见的,而property只是一个普通的名值对属性。

$('.qhdxImg').attr({src:'images/qhdx-2.png'})

显示单词写错了。

错误提示也是写.arrt is not a function.检查一下代码。

let obj=document.getElementById("XXXXXX")

jquery中用法:

设置属性:obj.attr("属性名",'属性值')

获取属性值:属性值=obj.attr('属性名')

原生用法:

设置属性:obj.setAttribute("属性名",'属性值')

获取属性值:属性值=obj.getAttribute('属性名')