document.getElementById()不起作用?(document.getElementById() doesn't work? [duplicate])

编程入门 行业动态 更新时间:2024-10-27 10:24:54
document.getElementById()不起作用?(document.getElementById() doesn't work? [duplicate])

没什么可说的,

<html> <body> <script> var x = document.getElementById('btn1'); alert(x); </script> <input type="button" id="btn1" value="Clickme" onclick="alert('1')" /> </body> </html>

警报消息是null而不是消息包含对象的细节或类似的东西。

问题是什么?

This question already has an answer here:

Why does jQuery or a DOM method such as getElementById not find the element? 8 answers

No much to say,

<html> <body> <script> var x = document.getElementById('btn1'); alert(x); </script> <input type="button" id="btn1" value="Clickme" onclick="alert('1')" /> </body> </html>

The alert message is null instead of a message contain details of the object or something like that.

What is the problem?

最满意答案

把你的脚本放在实际的元素之后,否则在你的JavaScript代码运行的时候,DOM中还没有这样的元素。

<html> <body> <input type="button" id="btn1" value="Clickme" onclick="alert('1')" /> <script> var x = document.getElementById('btn1'); alert(x); </script> </body> </html>

或者将您的脚本放入DOM就绪事件中,以确保在尝试操作DOM之前浏览器已完全加载DOM:

<html> <body> <script> window.onload = function() { var x = document.getElementById('btn1'); alert(x); }; </script> <input type="button" id="btn1" value="Clickme" onclick="alert('1')" /> </body> </html>

Put your script AFTER the actual element, otherwise by the time your javascript code runs, there's not yet such element in the DOM.

<html> <body> <input type="button" id="btn1" value="Clickme" onclick="alert('1')" /> <script> var x = document.getElementById('btn1'); alert(x); </script> </body> </html>

Alternatively put your script in a DOM ready event to ensure that the DOM is fully loaded by the browser before attempting to manipulate it:

<html> <body> <script> window.onload = function() { var x = document.getElementById('btn1'); alert(x); }; </script> <input type="button" id="btn1" value="Clickme" onclick="alert('1')" /> </body> </html>

更多推荐

alert,getElementById,null,电脑培训,计算机培训,IT培训"/> <meta name="des

本文发布于:2023-07-26 08:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1272922.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   getElementById   document   work   duplicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!