我正在尝试制作剪刀石头布游戏,这部分代码与我将如何获得用户选择有关。为了测试它是否正常工作,我想首先控制台记录选择。
<html>
<head>
<style>
.rockChoice {
font-size: 20px;
}
.scissorsChoice {
font-size: 20px;
}
.paperChoice {
font-size: 20px;
}
</style>
</head>
<body>
<div class="rockChoice isRock"><a href="#">Rock</a></div>
<div class="scissorsChoice"><a href="#">Scissors</a></div>
<div class="paperChoice"><a href="#">Paper</a></div>
<script>
function checkUserChoice() {
if (document.querySelector(".rockChoice").classList.contains(isRock)) {
userChoice = "rock";
} else if (document.querySelector(".scissorsChoice").classList.contains(isScissors)) {
userChoice = "scissors";
} else if (document.querySelector(".paperChoice").classList.contains(isPaper)) {
userChoice = "paper";
}
}
function checkUserChoice();
console.log('the user choice is ' + userChoice);
</script>
</body>
</html>
最佳答案
您的代码的第一个问题:
function checkUserChoice() { ... code here ... } // this is how to define functions
function checkUserChoice(); // that is not how to call functions
checkUserChoice(); // this is the way to call a function
您的代码的第二个问题:
...classList.contains(isPaper) // this will check if the class list contains a string
// however, you forgot the quotes
// otherwise, JS will think that what you need
// to search for is stored in a variable named isPaper
// which in your case, is not true
...classList.contains("isPaper") // this is what you meant to say
您的代码的第三个问题: 始终声明变量,不要只是即时使用它们
userChoice = "rock"; // userChoice has never been declared.
// it might work, but it is not good practice
声明变量将设置它们的作用域(全局/私有(private)函数等)..
var userChoice; //declare first
function my_function() {
...
userChoice = "something"; // assign later
...
}
<html>
<head>
<style>
.rockChoice {
font-size: 20px;
}
.scissorsChoice {
font-size: 20px;
}
.paperChoice {
font-size: 20px;
}
</style>
</head>
<body>
<div class="rockChoice isRock"><a href="#">Rock</a></div>
<div class="scissorsChoice"><a href="#">Scissors</a></div>
<div class="paperChoice"><a href="#">Paper</a></div>
<script>
var userChoice;
function checkUserChoice() {
if (document.querySelector(".rockChoice").classList.contains("isRock")) {
userChoice = "rock";
} else if (document.querySelector(".scissorsChoice").classList.contains("isScissors")) {
userChoice = "scissors";
} else if (document.querySelector(".paperChoice").classList.contains("isPaper")) {
userChoice = "paper";
}
}
checkUserChoice();
console.log('the user choice is ' + userChoice);
</script>
</body>
</html>
关于javascript - 为什么 if/then 对于 document.querySelector 不起作用?剪刀石头布游戏的部分代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53532076/