gpt4 book ai didi

javascript - 我如何才能使某些 Javascript 仅在有人单击链接或元素时运行?

转载 作者:行者123 更新时间:2023-11-29 19:40:14 24 4
gpt4 key购买 nike

我问这个问题是因为我在一个教程中制作了一个剪刀石头布游戏,并希望它仅在有人点击某些东西时运行。不是它自动运行的地方。请告诉我。 :)如果你想在这里为游戏编码

<script>
confirm("Open up your browsers console to see who wins")
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);
var compare = function (choice1, choice2)
{
if (choice1 === choice2) {
return "The result is a tie!";
}
else if (choice1 ==="rock") { // 1st Choice

if(choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";
}
}
else if (choice1 === "paper") { // 2nd Choice

if (choice2 === "rock") {
return "paper wins";
}
else {
return "scissors wins"
}

}
else if (choice1 === "scissors") { // 3rd Choice

if (choice2 === "rock") {
return "rock wins";
}
else {
return "scissors wins";
}
}
};
compare(userChoice,computerChoice);
</script>

最佳答案

大多数 HTML 元素响应事件。如果您想在单击文本时运行一个函数,您可以将文本放在一个 div 元素中,并使用调用您的函数的 onclick 事件。

<script>
function func1() {
alert("First function has been called");
}
function func2() {
alert("Second function");
}
</script>

This text does nothing
<div onclick="func1()">This does something</div>
This text does nothing
<div onclick="func2()">This does something else</div>
This text does nothing

关于javascript - 我如何才能使某些 Javascript 仅在有人单击链接或元素时运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23508502/

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