【问题标题】:How do I change a const value when a button is clicked?单击按钮时如何更改 const 值?
【发布时间】:2020-09-15 21:48:19
【问题描述】:

有人可以帮我将 console.log 行替换为可以帮助我根据单击的按钮更改 player.choice 值的内容吗?

const player = {
  currentChoice: null
}
const computer = {
  currentChoice: null
}



const choices = ["Lapis", "Papyrus", "Scalpellus"];

document.querySelector('#Lapis').onclick = setLapis
document.querySelector('#Papyrus').onclick = setPapyrus
document.querySelector('#Scalpellus').onclick = setScalpellus;

function setLapis(){
  console.log("Lapis");
}
function setPapyrus(){
  console.log("Papyrus");
}
function setScalpellus(){
  console.log("Scalpellus");
}

player.currentChoice = choices[0];
<button id="Lapis">Lapis</button>
<button id="Papyrus">Papyrus</button>
<button id="Scalpellus">Scalpellus</button>

【问题讨论】:

  • player.currentChoice = "青金石";
  • 这似乎对我不起作用

标签: javascript arrays function event-listener


【解决方案1】:

const player = {
  currentChoice: null
}
const computer = {
  currentChoice: null
}



const choices = ["Lapis", "Papyrus", "Scalpellus"];

document.querySelector('#Lapis').onclick = setLapis
document.querySelector('#Papyrus').onclick = setPapyrus
document.querySelector('#Scalpellus').onclick = setScalpellus;

function setLapis(){
  player.currentChoice = choices[0];
  console.log(player.currentChoice);
}
function setPapyrus(){
  player.currentChoice = choices[1];
  console.log(player.currentChoice);
}
function setScalpellus(){
  player.currentChoice = choices[2];
  console.log(player.currentChoice);
}
<button id="Lapis">Lapis</button>
<button id="Papyrus">Papyrus</button>
<button id="Scalpellus">Scalpellus</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    相关资源
    最近更新 更多