Javascript getElementById()为现有对象返回Null
在绘制数据驱动网格的页面底部附近,网格包包含以下代码Javascript getElementById()为现有对象返回Null,javascript,getelementbyid,Javascript,Getelementbyid,在绘制数据驱动网格的页面底部附近,网格包包含以下代码 <script type="text/javascript"> (function(window, document, undefined) { "use strict"; var gridColSortTypes = ["string", "string", "number", "number", "number", "number", "number", "number",
<script type="text/javascript">
(function(window, document, undefined) {
"use strict";
var gridColSortTypes =
["string", "string", "number", "number", "number", "number", "number", "number", "number", "number"],
gridColAlign = [];
var onColumnSort = function( newIndexOrder, columnIndex, lastColumnIndex ) {
var doc = document;
var offset = (this.options.allowSelections && this.options.showSelectionColumn)?1:0;
if( columnIndex !== lastColumnIndex ) {
if( lastColumnIndex > -1 ) {
doc.getElementById("stockHdr" + (lastColumnIndex-offset)).parentNode.style.backgroundColor = "";
}
doc.getElementById("stockHdr" + (columnIndex-offset)).parentNode.style.backgroundColor = "#f7f7f7";
}
};
...
})(this, this.document);
(功能(窗口、文档、未定义){
“严格使用”;
var gridColSortTypes=
[“字符串”、“字符串”、“数字”、“数字”、“数字”、“数字”、“数字”、“数字”、“数字”、“数字”],
gridColAlign=[];
var onColumnSort=函数(newIndexOrder、columnIndex、lastColumnIndex){
var doc=单据;
var offset=(this.options.allowSelections&&this.options.showSelectionColumn)?1:0;
如果(columnIndex!==lastColumnIndex){
如果(lastColumnIndex>-1){
doc.getElementById(“stockHdr”+(lastColumnIndex偏移量)).parentNode.style.backgroundColor=”“;
}
doc.getElementById(“stockHdr”+(列索引偏移量)).parentNode.style.backgroundColor=“#F7F7”;
}
};
...
})(这个,这个文件);
在调查指定的排序列颜色更改失败的原因时,我发现,尽管getElementById()查询的对象存在并在页面中运行,但在该函数中,这些getElementById()调用返回Null。实际上,从该函数进行的所有getElementById()调用都返回Null
为什么?我假设当您试图访问DOM内容时,它还没有准备好/可访问,请尝试在
窗口中包装您的代码。onload
:
window.onload = function(){
(function(window, doc, undefined) {
"use strict";
var gridColSortTypes =
["string", "string", "number", "number", "number", "number", "number", "number", "number", "number"],
gridColAlign = [];
var onColumnSort = function( newIndexOrder, columnIndex, lastColumnIndex ) {
var offset = (this.options.allowSelections && this.options.showSelectionColumn)?1:0;
if( columnIndex !== lastColumnIndex ) {
if( lastColumnIndex > -1 ) {
doc.getElementById("stockHdr" + (lastColumnIndex-offset)).parentNode.style.backgroundColor = "";
}
doc.getElementById("stockHdr" + (columnIndex-offset)).parentNode.style.backgroundColor = "#f7f7f7";
}
};
...
})(this, this.document);
};
您确定DOM元素存在并且在执行此代码时可以访问吗?尝试在window.onload中包装函数。另外(不相关且迂腐),为什么不直接调用外部闭包参数
doc
,而不是创建另一个var?