javascript - 如何让这个javascript同时在IE7和chrome中运行

标签 javascript

我正在开发一个使用框架的遗留应用程序,这一行让我感到困惑: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").innerTextdocument.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/

相关文章:

javascript - jQuery打印机(jQuery.print Element)无法在opera中打印多页

javascript - Firefox 插件 SDK : Loading addon file into iframe

javascript - 绕过本地主机的身份验证以在 Etherpad 中实现搜索

javascript - 循环中的 jQuery 单击事件被 float 属性破坏

javascript - 调整字体最大尺寸

javascript - 使用 Java 脚本编写某个函数

javascript - CoffeeScript 中的 ?= 与 ||=

javascript - 悬停时的颜色没有改变

javascript - 为什么 1 + '1' = '11' 但 1 *'1' = 1

javascript - 将项目保存为增量 json 差异?