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;
}
解决方案
是的你可以。事实上,您可以拥有多个元素,并为它们添加事件侦听器,这将为您提供添加的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;
}
推荐阅读
- java - Hibernate 尝试删除单向多对一关系中的父实体
- python - 达到最大索引时如何从头开始迭代列表
- javascript - 提交后react-hook-form字段刷新
- c# - 使用 Atan2 时移动角度
- c - 如何在计算机中执行最基本的门级操作?
- delphi - 如何在 Delphi 中使用 AES-256 GCM 进行加密
- r - 创建一个新列,其值与另一列的值对应
- flutter - 我有一个关于在 initstate 中有条件地导航到下一页的问题
- amazon-web-services - CloudFormation 模板中的 Aws Glue Crawler 重新抓取策略
- python - 尝试使用 Matplotlib 在 Python 中绘制动画