我有一个javascript函数,它通过ID从页面文档中获取元素,或者如果parentObj被传入,则从parentObj.document获取元素。
但是,在IE10中,当我不处于兼容模式时,访问parentObj.document返回"未定义"。使用 IE 开发人员工具,parentObj 具有文档成员,但它仅被视为泛型对象。可以将不同类型的对象传递到函数中。
示例代码:
function getJSObject(objID, parentObj)
{
if (parentObj != null)
{
return parentObj.document.getElementById(objID);
}
return document.getElementById(objID);
}
(不是实际的功能,这是我被允许发布的,以传达这个想法。
基本上,这在IE10兼容模式下工作,在IE10兼容模式之外无法正常工作。正确的方法是什么?
编辑:调用代码:
var selectionPage = objWindows[0].document.forms[sourceForm];
if (selectionPage)
{
var selectionControl = getJSObject(sourceControlID, selectionPage);
}
objWindows只是一个简单的全局级别数组,用于跟踪打开的弹出窗口。 sourceForm是从弹出窗口调用整体js函数的形式。
选项 1
有两种可行的解决方案。 理想情况下,您只需传入window
对象。
var selectionPage = objWindows[0];
var formElement = selectionPage.document.forms[sourceForm];
if (formElement)
{
var selectionControl = getJSObject(sourceControlID, selectionPage);
}
选项 2
另一种解决方案是更改getJSObject
以允许您从相关窗口传入 dom 元素。 我会将函数更改为以下内容:
function getJSObject(objID, objectFromWindow)
{
if (objectFromWindow != null && !!objectFromWindow.ownerDocument)
{
return objectFromWindow.ownerDocument.getElementById(objID);
}
return document.getElementById(objID);
}
你可以尝试这样的东西(未经测试):
function getJSObject(objID, parentObj) {
var parent = parentObj != null) ? parentObj : document;
var doc;
while(doc && Object.prototype.toString.call(doc) != "[object HTMLDocument]") {
doc = doc.parentNode;
}
return doc.getElementById(objID);
}