我想知道如何自动化和简化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;
}
发布于 2018-10-19 06:11:23
是的你可以。事实上,您可以拥有多个元素,并为它们添加一个事件侦听器,这将为您提供添加的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;
}
发布于 2018-10-19 06:09:43
inputs = document.getElementsByClassName('pick');
for (let i = 0; i < inputs.length; i++) {
inputs[i].onclick = function() { userInput = this.value; }
}
https://stackoverflow.com/questions/52883211
复制相似问题