zoukankan      html  css  js  c++  java
  • getAttribute()与attr() 和prop()的区别

    原文: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方法。

  • 相关阅读:
    XidianOJ 1099 A simple problem
    XidianOJ 1097 焊板子的xry111
    XidianOJ 1172 Hiking
    XidianOJ 1176 ship
    bzoj1912(树的直径)
    黑暗城堡(最短路径树)
    poj1639(k限制最小生成树)
    0-1分数规划
    tyvj1391(Kruskal)
    [Usaco2007 Nov]Cow Relays(矩阵乘法+floyd)
  • 原文地址:https://www.cnblogs.com/xi-li/p/14652438.html
Copyright © 2011-2022 走看看