节点属性的使用

两种方法

  • 元素节点.属性 或 元素节点[" "]

例:

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div class="box">中国</div>
    <script>
        var box = document.getElementsByClassName("box")[0];
        box.aaaa = "1111";

    </script>
</body>
  • 元素节点.方法

例:

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div class="box">中国</div>
    <script>
        var box = document.getElementsByClassName("box")[0];
        box.setAttribute("aaaa","2222");
        console.log(box.setAttribute("aaaa", "2222"));

    </script>
</body>

但是,当书写事件驱动程序时:

只有以下是正确的

    <style>
        button {
            width: 80px;
            height: 60px;
        }
        .current {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <button>按钮1</button>
    <button>按钮2</button>
    <button>按钮3</button>
    <button>按钮4</button>
    <button>按钮5</button>
    <script>
        var btn = document.getElementsByTagName("button");
        btn[0].setAttribute("backgroundColor","yellow");

        for(var i=1;i<btn.length;i++){
            btn[i].onmouseover = function(){
                this.className = "current"; 
            }
        }
    </script>
</body>

以下两种,错误提示均为:Cannot set property 'className' of undefined

Cannot read property 'setAttribute' of undefined,不知道为啥

   <script>
        var btn = document.getElementsByTagName("button");
        // btn[0].setAttribute("backgroundColor","yellow");

        for(var i=1;i<btn.length;i++){
            btn[i].onmouseover = function()
                // btn[i].className = "current";错误
                // btn[i].setAttribute("backgroundColor","yellow"); 错误
            }
        }
    </script>

原因为:运行完成后,i变为5,因为未触发事件之前,先进行for循环,只加载函数名,不加载函数体。即只遍历li[i].onmouseover部分,而函数体的内容并未运。以下列子alert,即I均为5

   <script>
        var li = document.getElementsByTagName("li");
        var span = document.getElementsByTagName("span");
        for(var i=0;i<li.length;i++){
            li[i].onmouseover = function(){
                this.className = "bgc";
                alert(i);
            }
            li[i].onmouseout = function(){
                this.className = "";
            }
        }
    </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值