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 answersNo 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
发布评论