登录

javascript - JS问题:请教一下 getAttribute()获取属性的问题。

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
#box{width:100px; height:100px; background:red;}    
</style>
</head>
<body>
    <p id="box" haha="哈哈"></p>    

<script type="text/javascript">
    window.onload=function(){
        var oBox=document.getElementById('box');

        oBox.index='测试';
        //第一组
        alert(oBox.haha); // undefined
        alert(oBox.getAttribute('haha')) // 哈哈
        //第二组
        alert(oBox.index); // 测试
        alert(oBox.getAttribute('index')) // null
        
    };
</script>    
</body>
</html>

第一组中:
oBox.haha:我在p中设置了haha属性,为什么是未定义?但用oBox.getAttribute('haha'),却能得到haha属性值“哈哈”。

第二组中:
oBox.index。获取到index属性的属性值,oBox.getAttribute('index')却返回null。

请问这两组结果应该怎么理解?谢谢!

# JavaScript
ringa_leeringa_lee2184 天前451 次浏览

全部回复(1) 我要回复

  • 黄舟

    黄舟2017-04-10 16:03:21

    你给p设置的hahaattribute 而你直接用OBox.haha调用的是oBox对象上的haha,而oBox对象上是没有haha的所以返回的是undefinedoBox.index="测试"的结果是,如果oBox对象有index属性则用测试覆盖原来的值,如果没有则新增一个index属性并初始化为测试

    对象上的属性和html标签上的attibute不是一个东西

    html 上的attribute 就用getAttribute访问,对象上的是直接.出来的。

    回复
    0
  • 取消回复发送