首页 > 解决方案 > 如何在 javascript 中自动执行指令

问题描述

我想知道如何自动化和简化 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;
}

标签: javascript

解决方案


是的你可以。事实上,您可以拥有多个元素,并为它们添加事件侦听器,这将为您提供添加的value. 假设您有 3 个项目,所有项目都带有 class 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;
}

推荐阅读