我有正在使用实例化CSS 开发的 HTML 代码。但是,我目前无法从输入字段中读取数据
<form id="two_player">
<div class="row">
<div class="input-field col s6">
<input placeholder="Apelido do jogador 1" id="two_player_one" type="text" class="validate">
<label for="first_name">Jogador 1:</label>
</div>
<div class="input-field col s6">
<input placeholder="Apelido do jogador 2" id="two_player_two" type="text" class="validate">
<label for="player_two">Jogador 2:</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input placeholder="Número de cartas da 1ª rodada" id="two_player_one_round_one" type="number" min="0" max="13" class="validate">
<label for="player_one_round_one">Rodada 1:</label>
</div>
<div class="input-field col s6">
<input placeholder="Número de cartas da 1ª rodada" id="two_player_two_round_one" type="number" min="0" max="13" class="validate">
<label for="player_two_round_one">Rodada 1:</label>
</div>
</div>
</form>
如何使用 JavaScript 读取每个输入字段?
答案 0 :(得分:3)
您可以使用getElementById()
查找元素,并使用.value
公开其值。
let two_player_one = document.getElementById('two_player_one').value;
let two_player_two = document.getElementById('two_player_two').value;
let two_player_one_round_one = document.getElementById('two_player_one_round_one').value;
let two_player_two_round_one = document.getElementById('two_player_two_round_one').value;
getElementById()
here的MDN文档。答案 1 :(得分:1)
let val = document.getElementById('an input field ID').value;
for (var i = 0; i < document.getElementsByTagName('input').length; i++) {
console.log(document.getElementsByTagName('input')[i].value);
}
基本上是这样的。
通过for
循环,您可以遍历所有输入元素和console.log()
的值(或对值进行任何操作)。第一个基于元素ID
定位元素并获取其值。