gpt4 book ai didi

JavaScript 按钮在 Chrome 和 IE 中完美触发,但在 Firefox 中不起作用

转载 作者:行者123 更新时间:2023-12-02 18:13:50 24 4
gpt4 key购买 nike

我确信这个标题看起来像以前被问过的问题,但我已经搜索过这个问题的答案,但找不到它。

我对编码真的很陌生,所以请原谅我犯的任何明显的错误。

我正在编写的代码的上下文:我正在上游戏设计课,我决定开始一个制作 HTML JS 游戏的个人项目。

我知道代码可能很粗糙/糟糕/绝对不是最好的做事方式,但它会继续如此,直到我提高我的技能(或者得到关于如何做的建议)改进它)。

我需要什么帮助:在两到三周的时间里,我不知道如何在 if else 语句内实现时显示按钮。

像这样:

if(condition)
{
document.write("text");
//desired button here
}
else
{
//Backup code
}

最终我想出了两种方法来做到这一点(对于 Chrome 和 Internet Explorer)。

第一种方式:

function myFunction()
{
document.close();
document.write("text");
/* There will be buttons in here
too when I get things working. */
}

//In separate script tags
/* myFunction() dwells in the head of the
page while the if statement is in the body
and another function*/

if(condition)
{
document.write("text");
var gameElement=document.createElement("BUTTON");
var text=document.createTextNode("CLICK ME");
gameElement.appendChild(text);
gameElement.onclick = myFunction;
document.body.appendChild(gameElement);
}
else
{
//Backup code
}

第二种方式:

(相同的功能,它们都在相同的位置)。

if(condition)
{
document.write("text");
var gameElement;
gameElement = document.createElement('input');
gameElement.id = 'gameButton';
gameElement.type = 'button';
gameElement.value='Continue';
gameElement.onclick = myFunction;
document.body.appendChild(gameElement);
}

这对我来说效果很好。

虽然它在 IE 和 Chrome 中工作得很好,但在 Firefox 中却不起作用。

经过我对这个按钮投入了多少时间和研究,我很想知道为什么它不会出现在 Firefox 中。我读过很多关于 Firefox 的文章,以及 .onclick 如何不起作用或者必须启用或禁用 JavaScript 之类的内容。我只是有点困惑。

我也愿意提出任何真实/相关的建议。

最佳答案

我设置了这个fiddle 。我删除了您的 document.write() 调用,因为它们在 JSFiddle 中是不允许的,并将您的条件更改为 true 以便代码可以工作,并且它可以在 FF24 中工作。

document.write() 可能是导致您的问题的原因。无论如何,这都是不好的做法,因为它可能会导致重新解析文档,或者删除整个文档并重新开始写入。您已经在使用一些 DOM 操作来添加按钮。我建议您对您考虑使用 document.write() 执行的任何操作执行同样的操作。

关于JavaScript 按钮在 Chrome 和 IE 中完美触发,但在 Firefox 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19483003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com