原文:http://www.voidcn.com/article/p-suniitrl-bse.html  https://www.jb51.net/article/114876.htm

我遇到的问题:aa是拼接的html,pro是自定义的属性值, console.log(aa.getAttribute("pro"));报错aa.getAttribute is not a function,因为aa是boolean,不是元素(object Element).

label.addEventListener('click', function(e) {
var aa=e.target.content;
console.log(e);

console.log($(aa).attr("pro"));

})

getAttribute()与attr() 和prop()都是获取属性值的方法,但有区别。
主要区别:
调用 getAttribute() 的主体必须是元素(Object Element)
调用 attr() 的主体必须是对象(Object Object)
正确方式:
var div = document.getElementById('test');
//获取的div是[object HTMLDivElement]
alert(div.getAttribute('custom'));

错误方式:因为通过 JQ 选择器获取 div,此时的 div 是对象(Object)也就无法调用 getAttribute() 方法
var div = $('#test');
//获取的div是[object Object]
alert(div.getAttribute('custom'));

div.setAttribute("属性","值");设置属性
正确方式:
var div = $('.test');
//获取的div是[object object]
alert(div.attr('custom'));
错误方式:因为attr()是“获取一组相匹配元素中首个元素的属性值”。
描述中的“一组元素”应该指的是对象(Object),而不是多个元素组成的集合(HTMLCollection)
var div = document.getElementsByClassName('test'); //获取的div是[object HTMLCollection] alert(div.attr('custom'));


$('test').attr("key","value")设置属性

prop()函数的结果:

      1.如果有相应的属性,返回指定属性值。

      2.如果没有相应的属性,返回值是空字符串。


attr()函数的结果:

      1.如果有相应的属性,返回指定属性值。

      2.如果没有相应的属性,返回值是undefined。

总结:

     对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。

     对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。

posted on 2021-04-13 11:38  多年小白  阅读(144)  评论(0编辑  收藏  举报