gpt4 book ai didi

JavaScript 不会在页面上写入

转载 作者:行者123 更新时间:2023-12-01 00:30:12 25 4
gpt4 key购买 nike

我正在制作这个游戏,其中有 2 个盒子,如果您单击正确的一个,您就会获胜。我遇到这个问题,当玩家单击一个框时,它不会显示他是赢了还是输了,只有在检查元素时才能看到。

我已经尝试将“console.log”更改为“document.write”,但它不起作用。有人可以告诉我当玩家点击一个框时如何写一些东西吗?

var button1 = document.getElementById('button1')
var button2 = document.getElementById('button2')
var array = [('button1'), ('button2')];
var winItem = 1;

function getRandomItemNum(length) {
return Math.ceil(Math.random() * length)
}

function recalculateWinItem() {
winItem = getRandomItemNum(array.length);
}

function checkIsWin(buttonNum) {
console.log(`Clicked ${buttonNum}. Win item: ${winItem}`);
console.log(buttonNum === winItem ? "You won" : "You lose");
}

recalculateWinItem();
<button id="button1" onclick="checkIsWin(1)" style="height: 200px; width: 200px; position: absolute; left: 33%; background-color: black; color: blue;">1</button>
<button id="button2" onclick="checkIsWin(2)" style="height: 200px; width: 200px; position: absolute; right: 33%; background-color: black; color: red;">2</button>

最佳答案

向页面添加容器

<div id="result"></div>

并使用

document.getElementById("result").innerText = winItem ? "You won" : "You lose"; // or innerHTML if tags in the result

切勿在页面加载后使用 document.write,因为它会删除页面和脚本

function getRandomItemNum(length) {
return Math.ceil(Math.random() * length)
}

function recalculateWinItem() {
winItem = getRandomItemNum(array.length);
}

function checkIsWin(buttonNum) {
var text = `Clicked <b>${buttonNum}</b>. Win item: ${winItem}; `
text += buttonNum === winItem ? "You won" : "You lose";
document.getElementById("result").innerHTML = text;
}
var array = [...document.querySelectorAll("#container .but")].map(function(but) {
but.addEventListener("click",function() { checkIsWin(+this.id.replace("button",""))})
return `(${but.id})`
});
window.addEventListener("load", function() {
document.getElementById("start").addEventListener("click", recalculateWinItem)
recalculateWinItem();
})
.but {
height: 200px;
width: 200px;
position: absolute;
top: 10%;
background-color: black;
}

#button1 {
left: 33%;
background-color: black;
color: blue;
color: blue;
}

#button2 {
right: 33%;
background-color: black;
color: red;
}
<div id="result"></div>
<hr/>
<div id="container" style="width:100%">
<button id="button1" class="but">1</button>
<button id="button2" class="but">2</button>
</div>
<button type="button" id="start">Start</button>

关于JavaScript 不会在页面上写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58625200/

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