ASP.NET:为什么我的 JavaScript 对象设置为 null?
我有一个包含以下行的 :
var tbl = document.getElementById("<%= this.tblSelection.ClientID %>");
...但是 tbl
最终总是被设置为 null
。
该表的声明如下:
<asp:Table ID="tblSelection" runat="server" CellPadding="2" CellSpacing="0"
cols="1" style="position: absolute; top: 0%; right: 0%">
脚本和表都位于同一个母版页文件中。
可能是什么原因造成的?
编辑:我应该提到这个脚本是在 onload
上执行的
I have a <script>
that contains this line:
var tbl = document.getElementById("<%= this.tblSelection.ClientID %>");
... but tbl
always ends up being set to null
.
The table is declared like this:
<asp:Table ID="tblSelection" runat="server" CellPadding="2" CellSpacing="0"
cols="1" style="position: absolute; top: 0%; right: 0%">
Both the script and the table are in the same master page file.
What could be causing this?
EDIT: I should mention that this script is executed on onload
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜你的 JavaScript 代码在浏览器有机会完全渲染表格之前就已经执行了。此时,页面的 DOM 将不完整,并且
getElementByID
函数将无法找到该表,因为它还不存在!做这个实验:
当您的页面首次加载时,这将显示“null”。但是,如果您添加一个按钮来再次调用此方法,您将看到
tbl
被填充。I am guessing your JavaScript code is executing before your browser has a chance to fully render the table. At this point, the DOM of the page will not be complete and the
getElementByID
function will not be able to find the table because it doesn't exist yet!Do this experiment:
This will show you "null" when your page first loads. If you add a button to call this method again, however, you'll see that
tbl
gets populated.MrGumbe 和 Valera 关于 Javascript 的时间安排是正确的。但我看到这种情况的发生还有另一个原因。我们有过服务器端逻辑设置 tblSelection.Visible=false 的实例,这意味着它甚至不会发送到浏览器。像您这样的客户端代码会运行寻找 ID 和 bang。
MrGumbe and Valera are right about the timing of your Javascript. But I've seen this happen for another reason. We have had instances where server-side logic set tblSelection.Visible=false which means it isn't even emitted to the browser. Client-side code like yours runs looking for the ID and bang.
尼克是正确的。该表尚未解析/构造。
尝试将
getElementById
代码移至 document.ready 事件。顺便说一句,jQuery 为文档事件等提供了一个很好的包装器。
这是代码片段:
Nick is correct. The table is not parsed/constructed yet.
Try to move
getElementById
code to document.ready event.BTW, jQuery provides a nice wrapper around document events and more.
Here is code snippet: