![](/img/trans.png)
[英]document.getElementById not finding element in ASP.NET form
[英]document.getElementById fails on <div> in asp.net
我有以下脚本在包含Google Map控件的div
上设置height
:
<script>
var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
//alert("Height:" + height)
document.getElementById('divMap').setAttribute("style", "width:" + height);
</script>
再往下, div
被定义为:
<div id="divMap" class="col-md-6" style="min-height: 800px; height:100%">
<map:GoogleMap ID="GoogleMap1" runat="server" Width="100%" Height="100%">
</map:GoogleMap>
<map:GoogleMarkers ID="GoogleMarkers1" TargetControlID="GoogleMap1" runat="server" OnClick="GoogleMarkers1_Click" />
</div>
该脚本在加载时运行良好。 我得到了浏览器窗口的height
。
但是, getElementById()
总是失败。
就像脚本运行时div
不存在一样。 如果我选择调试页面,则只显示<script>
标记。
我错过了什么,但是什么?
或者是否有另一种方法来设置asp.net中div
的height
?
我相信这是因为您在加载正文之前首先加载script
标记。 当script
首先加载时,它将查找body
中尚不存在的元素。 因此无法找到该元素。 您需要将script
放在底部。
像这样:
<body>
<div id="divMap">
...
</div>
<script>
...
</script>
</body>
您需要先加载元素。 所以元素将存在于体内。
错误说divMap
未找到null
或undefined
什么意味着你在DOM中找不到脚本代码的意思,换句话说,脚本试图在尚未加载时获取该元素。
因此,为了确保在脚本运行之前加载所有DOM元素,您可以在ready函数中添加代码,如:
document.addEventListener("DOMContentLoaded", function(event) {
//Your code here
});
注意:如果您可以控制页面结构,则可以将JS与正文中的HTML分开,因为混合它们不是一个好习惯。
我认为问题是你在DOM之前尝试访问div。 尝试这个:
<html>
<head>
</head>
<body>
<div id="divMap" class="col-md-6" style="min-height: 800px; height:100%">
<map:GoogleMap ID="GoogleMap1" runat="server" Width="100%" Height="100%">
</map:GoogleMap>
<map:GoogleMarkers ID="GoogleMarkers1" TargetControlID="GoogleMap1" runat="server" OnClick="GoogleMarkers1_Click" />
</div>
<script>
(function() {
/var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
//alert("Height:" + height)
document.getElementById('divMap').setAttribute("style", "width:" + height);
})();
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.