我正在开发一个使用框架的遗留应用程序,这一行让我感到困惑:myName = document.anchors("mySettings").innerText;
它在 IE7 中工作正常,但在 Chrome 中工作正常它说:
未捕获类型错误:对象#的属性“anchors”不是函数
事实证明,要使其在 Chrome 中工作,唯一需要做的就是将圆括号 () 替换为方括号 []。问题是,现在它无法在 Internet Explorer 中运行。 IE 说:'document.anchor.mySettings.innerText' 为 null 或不是对象。
好的,所以我尝试检查 document.anchors
是否是一个像这样的函数: if (typeof document.anchors === "function") {
以及如果它是,使用圆括号(因此它在 IE 中有效),否则使用方括号(对于 Chrome)。没用。它仍然进入两者的 else block ,因此显然它也不是 IE 中的函数。
然后我尝试检查 document.anchors("mySettings").innerText
和 document.anchors["mySettings"].innerText
是否为空或不是对象像这样: if (document.anchors["mySettings"].innerText !== null || document.anchors["mySettings"].innerText !== "object") {
为了解决那个IE错误。还是没用。
这段代码有问题吗?或者有没有我忽略的更简单的方法? 基本上我需要的是这样的:
if IE {
myName = document.anchors("mySettings").innerText;
} else (if chrome) {
myName = document.anchors["mySettings"].innerText;
}
最佳答案
检测浏览器总是错误!相反,尝试一个功能,然后尝试另一个。在这种情况下,检查属性(Chrome)会更容易一些:
var anchor = document.anchors.mySettings;
if (!anchor) {
anchor = document.anchors("mySettings");
}
myName = anchor.innerText;
另外,你在 Firefox 中尝试过这个吗?歌剧?苹果浏览器?确保!世界上不仅有两种浏览器。
坦率地说,无论如何你都不应该使用命名 anchor ;给它们id
,使用document.getElementById
一致地访问它们,并保持相同的哈希行为。
<a href="http://example.com/" <del>name="mySettings"</del> id="my-settings">
var myName = document.getElementById('my-settings').innerText;
另请注意,textContent
是元素文本内容的标准属性;为了支持 IE7,我仍然会使用 firstChild.nodeValue
。
关于javascript - 如何让这个javascript同时在IE7和chrome中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23832020/