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


代码:


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

<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:我在div中设置了haha属性,为什么是未定义?但用oBox.getAttribute('haha'),却能得到haha属性值“哈哈”。

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

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

web前端开发 JavaScript

ayair 8 years, 7 months ago

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

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

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

zxzxzx answered 8 years, 7 months ago

Your Answer