【问题标题】:How to obtain a user input value from an image input in Javascript?如何从 Javascript 中的图像输入中获取用户输入值?
【发布时间】:2020-02-19 23:24:02
【问题描述】:

//const choices = ['Rock', 'Paper', 'Scissors'] in image form
const choices = window.document.getElementsByClassName('Images');
console.log(choices)

var userInput = window.document.getElementsByTagName('input')
console.log(userInput)


//take the image input and use it as a variable for the playerSelection part.
function playerSelection() {
    let answer = prompt('Rock, paper, scissors').toLowerCase()
    return answer
}
<div class="Options">
    <input type ="image" class="Images" src ="https://image.flaticon.com/icons/svg/925/925141.svg" alt=""/>
    <input type ="image" class="Images" src="https://image.flaticon.com/icons/svg/2583/2583491.svg" alt style="padding-left: 50px; padding-right: 50px;">
    <input type ="image" class="Images" src="https://image.flaticon.com/icons/svg/494/494672.svg" alt="">
    </div>

所以我要做的是在用户单击其中一张图片时从 HTML 文件中获取用户输入。所以我以后可以在我的 javascript 文件中使用它并将其保存到一个变量中。我已经尝试过 getElementsByTagName 但开发人员控制台中没有真正显示任何内容。我不确定如何使用谷歌开发者工具测试用户输入,以便我知道我的代码运行正常。

【问题讨论】:

  • 你知道如何监听元素上的click 事件吗?

标签: javascript html dom syntax


【解决方案1】:

图像输入就像按钮一样。你应该给每个输入一个值。然后添加一个点击事件监听器,获取被点击按钮的值。

//const choices = ['Rock', 'Paper', 'Scissors'] in image form

const output = document.querySelector("#output");
const choices = document.querySelectorAll('.Images');

choices.forEach(i => i.addEventListener("click", function() {
  playerSelection(this.value)
}));

//take the image input and use it as a variable for the playerSelection part.
function playerSelection(answer) {
  output.innerText = answer;
}
.Images {
  width: 100px;
  height: 100px;
}
<div class="Options">
  <input type="image" value="rock" class="Images" src="https://image.flaticon.com/icons/svg/925/925141.svg" alt="" />
  <input type="image" value="paper" class="Images" src="https://image.flaticon.com/icons/svg/2583/2583491.svg" alt style="padding-left: 50px; padding-right: 50px;">
  <input type="image" value="scissors" class="Images" src="https://image.flaticon.com/icons/svg/494/494672.svg" alt="">
</div>
You selected: <span id="output"></span>

【讨论】:

  • 嗯,我有点明白发生了什么,但是添加值对输入标签有什么作用?
  • 它允许您通过使用this.value来判断点击了哪个输入。
猜你喜欢
  • 1970-01-01
  • 2021-06-14
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 2012-11-12
相关资源
最近更新 更多