JS-用ID值直接操作DOM

用ID值直接操作DOM

如果一个元素有ID属性,并且window对象没有同名的属性,比如‘history’,‘location’,那么window对象会赋予一个属性,它的名字是id属性的值,而它们的值指向表示文档元素的HTMLElement对象。

但是只是知道就好,一般不这么用。

<body>
<input type="button" id="btn" value="按钮">
<input type="button" id="history" value="按钮">
<script>
    btn.onclick=function(){
        console.log('hello');   //结果弹出 --hello
    }
    location.onclick=function(){
        console.log('location');  //无任何输出--因为window自带locaiton属性,此时window的location属性,覆盖了id为location的标签
    }
</script>
</body>

  

原文地址:https://www.cnblogs.com/Helen-code/p/12314036.html