解决document.getElementBy系列方法获取不到对象的问题

解决document.getElementBy系列方法获取不到对象的问题,第1张

解决document.getElementBy系列方法获取不到对象的问题

getElementById取不到对象

在浏览器进行文档解析时是有顺序的,当页面加载完毕之前,或者说在相应的DOM对象加载完毕之前,对应的对象是不能获取到的。


看下面代码:

<script>
    var temp = document.getElementById("div");
    alert(temp);
</script>
<body>
<div id="div">
    <input name="username" id="username" type="text">
    <button id="btn">按钮</button>
</div>
</body>

在这段代码中,document.getElementById(“div”)是获取不到对象的,且alert(temp)将会d出null;

这是因为当浏览器解析到script标签中的代码时,body中的DOM元素还没有加载完毕,自然取不到任何东西。


解决方法:将script中的代码移到body元素之后,

<body>
<div id="div">
    <input name="username" id="username" type="text">
    <button id="btn">按钮</button>
</div>
<script>
    var temp = document.getElementById("div");
    alert(temp);
</script>
</body>

或者加上window.onload

<script>
window.onload = function(){
    var temp = document.getElementById("div");
    alert(temp);
    }
</script>

总结

以上所述是小编给大家介绍的解决document.getElementBy系列方法获取不到对象的问题,希望对大家有所帮助,也非常感谢大家对脚本之家网站的支持!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/619664.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-15
下一篇 2022-04-15

发表评论

登录后才能评论

评论列表(0条)

保存