【问题标题】:javascript code works in IE and Chrome but not in Firefoxjavascript 代码在 IE 和 Chrome 中有效,但在 Firefox 中无效
【发布时间】:2026-01-06 22:20:03
【问题描述】:

以下代码 sn-ps 在 IE 和 Chrome 中有效,但在 Firefox 中无效,我不知道为什么。

对于这个 sn-p,当在 IE 和 Chrome 中打开时,网页中会出现两个到 Google 的链接,但在 Firefox 中什么都没有出现。它位于body标签中的一个脚本标签中。

var varOne = document.createElement("a")
varOne.setAttribute("href", "http://www.google.com")
varOne.innerText = "Google"
document.body.appendChild(varOne) //attach the node to the body

var varOne = document.createElement("a")
varOne.setAttribute("href", "http://www.google.com")
varOne.textContent = "Google"
document.getElementById("bodyID").appendChild(varOne) //attach the node to the body




对于这个,您单击按钮转到 yahoo.com。当您按下浏览器的后退按钮时,您会返回到先前的页面,但 javascript 将再次运行,迫使浏览器返回到 yahoo。一旦您离开了原始页面,您将无法返回并停留在那里而不会被重定向到 yahoo。这就是在 IE 和 Chrome 中发生的事情(我只是为了学习目的),但我不明白为什么它在 Firefox 中不起作用。当您从 Yahoo 返回原始页面时,Firefox 不会像其他两种浏览器那样强制浏览器前进。

<body>
<form>

    <input type="button" onclick="javascript: window.location='http://www.yahoo.com' "/>

</form>

<script type="text/javascript">

    alert("Problem?")
    window.history.forward()     
</script>
</body>

【问题讨论】:

  • varOne.innerText = "Google" 我认为 Firefox 不再支持innerText,您需要使用textContent 或只使用innerHTML
  • 原来我的代码的其他部分在 Firefox 中无效,所以我修复了它,现在它可以工作了,除了 Firefox 不支持或以不同方式实现的部分,例如你和 Xander指出。谢谢大家。

标签: javascript internet-explorer google-chrome firefox


【解决方案1】:

尝试将1 传递给forward 方法:

window.history.forward(1);

如果它不起作用,那么您可能不走运,因为这似乎是浏览器制造商之间的可用性灰色区域。允许JavaScript(不是用户)在没有他/她直接参与的情况下更改当前页面是一个可用性问题——类似于不断触发pop-up/pop-under窗口。

【讨论】:

  • 不幸的是,通过 1 并没有什么不同。