所以我得到 4 个值作为数字:
<h3 class="u-text-size-h6"> </h3>
<div class="js-numstepper tiempo">
<input class="tiempos" type="number" min="0" max="60">
</div>
</div>
和:
var tiempoInstruccion = document.getElementsByClassName('tiempos');
然后我想将所有值转换为字符串,因为我有一个函数不能仅处理数字和文本。
我尝试过这个:
var stringTiempo = tiempoInstruccion.toString();
并尝试用循环来做它
我遇到的主要问题是这个函数:
var tiempoInstruccion = document.getElementsByClassName('tiempos');
var seleccionTiempo = [];
for (var i = 0; i < tiempoInstruccion.length; i++) {
var element = tiempoInstruccion[i].toString();
var strSel = element.options[element.selectedIndex].text;
seleccionTiempo.push(strSel);
}
我需要将这些值推送到这个数组
var seleccionTiempo = []
还尝试更改
element.options[element.selectedIndex].text;
到
element.options[element.selectedIndex].value;
我收到此消息:
类型错误:element.selectedIndex未定义
我确信它是因为数组不是字符串。
最佳答案
您可以使用以下函数来提取您的输入值
var tiempoInstruccion = [];
var seleccionTiempo = [];
function updatevalues(){
var tiempoInstruccion = document.getElementsByClassName('tiempos');
seleccionTiempo = [];
for(var i=0;i<tiempoInstruccion.length;i++){
var val = tiempoInstruccion[i].value;
if(val.length>0){
seleccionTiempo.push(val);
}
}
console.log(seleccionTiempo);
}
<div>
<h3 class="u-text-size-h6"> </h3>
<div class="js-numstepper tiempo">
<input class="tiempos" type="number" min="0" max="60">
</div>
</div>
<div>
<h3 class="u-text-size-h6"> </h3>
<div class="js-numstepper tiempo">
<input class="tiempos" type="number" min="0" max="60">
</div>
</div>
<div>
<h3 class="u-text-size-h6"> </h3>
<div class="js-numstepper tiempo">
<input class="tiempos" type="number" min="0" max="60">
</div>
</div>
<div>
<h3 class="u-text-size-h6"> </h3>
<div class="js-numstepper tiempo">
<input class="tiempos" type="number" min="0" max="60">
</div>
</div>
<div>
<input type="button" value="Update" onclick="updatevalues()">
</div>
关于javascript - 使用 getElementsByClassName 将多个值更改为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58371817/