我想知道如何自动化和简化 JavaScript 代码。 例如,我有 3 个按钮:
<button id="rock" class="pick" value="rock">rock</button>
<button id="paper" class="pick" value="paper">paper</button>
<button id="scissors" class="pick" value="scissors">scissors</button>
我选择这些元素 3 次。所以我的问题是如何仅用一条指令或函数来实现它?
var userInput = '';
document.getElementById('rock').onclick = function() {
userInput = 'rock';
}
document.getElementById('paper').onclick = function() {
userInput = 'paper';
}
document.getElementById('scissors').onclick = function() {
userInput = 'scissors';
}
我只是想知道我是否可以做这样的事情:
document.getElementById(element).onclick = function() {
userInput = element.value;
}
最佳答案
是的,你可以。事实上,您可以拥有多个元素,并为它们添加一个事件监听器,这将为您提供它们的附加值。假设您有 3 个项目,全部具有 gameCommands
类。然后你会做这样的事情:
const commands = document.querySelectorAll(".gameCommands")
const userInput;
commands.forEach(command => command.addEventListener("click", getValue)
function getValue(){
// THIS represents the element from which we call the function in this case.
userInput = this.value;
}
关于javascript - 如何在 JavaScript 中自动执行指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52883211/