javascript - 如何在 JavaScript 中自动执行指令

标签 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;
}

最佳答案

是的,你可以。事实上,您可以拥有多个元素,并为它们添加一个事件监听器,这将为您提供它们的附加值。假设您有 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/

相关文章:

javascript - 如何编写一个正则表达式 'and NO whitespaces' ?

javascript - 当上面显示大量内容时(因此导致滚动),保持页面垂直固定在元素上

javascript - 监听VueJS父组件中的事件调用方法

javascript - 如何重写它,以便它不会触发复选框

javascript - 如何在个人资料图像标签中应用 onchange 图像预览

javascript - 如何使用 React 路由器手动触发路由?

javascript - 为什么即使在重载引用的函数后,引用函数的 javascript 变量仍保持不变?

javascript - html中的图像预览错误

javascript - 使用 Material-ui 传递数据以显示表信息时出错

javascript - AngularJS指令: Attaching a function from the controller to ng-click