关于javascript的getelementbyid得到的为啥为null
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于javascript的getelementbyid得到的为啥为null相关的知识,希望对你有一定的参考价值。
<html>
<head>
<style type="text/css">
#temp
font-size:150px;
color:red;
</style>
</head>
<body>
<script type="text/javascript">
var x= new Array();
x = document.getElementById('temp');
alert(x);
</script>
<div id="temp">123456</div>
</body>
</html>
<html>
<head>
<style type="text/css">
#temp
font-size:150px;
color:red;
</style>
</head>
<body>
<div id="temp">123456</div>
<script type="text/javascript">
var x= new Array();
x= document.getElementById("temp");
alert(x);
</script>
</body>
</html>
这样写才可以.....
其实你这个语句是有问题的.我想你要得到的是DIV里面的值吧.....这样是得不到值的....这样只是把DIV这个对象给了X...所以最后哪怕调式成功也只是显示OBJECT,如果想得到它里面的内容..加上innerHTML或者innerText..就可以了.如
<html>
<head>
<style type="text/css">
#temp
font-size:150px;
color:red;
</style>
</head>
<body>
<div id="temp">123456</div>
<script type="text/javascript">
var x= new Array();
x= document.getElementById("temp").innerText;
alert(x);
</script>
</body>
</html> 参考技术A 因为<script></script>放到了<div></div>的前面了
如果放到后面 可以获得 [object] 这个结果 参考技术B 语句没错 但是div 没有value 这个属性
所以取值时告诉x未定义(undefined)
你把div换成文本框试试 肯定能取到值 参考技术C x是数组
以上是关于关于javascript的getelementbyid得到的为啥为null的主要内容,如果未能解决你的问题,请参考以下文章