我试图获取输入的值并将其保存在数组中。 我想检测用户文本0的时间,并且我想在0之前对数组中的所有值求和。
这是我的代码:
<form id="demo">
<input type="number" id="lala">
<button onclick='funsuma(this.form.lala.value)' > NO <button/>
</form>
<script>
var global = [];
var suma = 0;
function funsuma(valor) {
global.push(valor);
for (i = 0; i < global.length; i++) {
if (global[i] == 0) {
suma += parseInt(global[i], 10);
alert("Es 0, tu suma es: " + suma);
return false;
} else {
//alert(global[i]);
document.getElementById("demo").innerHTML = "<input type='number' id='lala'> <button value='Envia' onclick='funsuma(this.form.lala.value)'> NO <button/>";
return false;
}
}
//console.log("global");
}
</script>
答案 0 :(得分:1)
你可以做到
var global = [];
function funsuma(valor) {
var suma = 0;
//need to make sure valor is a number
global.push(+valor);
if (valor == 0) {
for (i = 0; i < global.length; i++) {
suma += global[i];
}
alert("Es 0, tu suma es: " + suma);
//based on your logic you need to see whether to reset the array
}
return false;
}
<form id="demo">
<input type="number" id="lala" />
<button onclick='return funsuma(this.form.lala.value)'>NO</button>
</form>
答案 1 :(得分:0)
你真的不需要一个表格,也不需要清除innerHtml并不断重置它。您可以使用事件侦听器并在js中设置输入的值。
<input type="number" id="lala" />
<button type="button" id="sum"></button>
(function(document){
var input = document.getElementById('lala');
var button = document.getElementById('sum');
var global = [];
var buttonClick = function(e){
e.preventDefault();
if(!isNaN(input.value)){
if(input.value === 0){
var sum = 0;
for(var i = 0; i < global.length; i++){
sum += global[i];
}
alert('Sum is ' + sum);
global.splice(0, global.length);
} else{
global.push(input.value);
input.value = '';
}
} else{
//if they somehow get a non-number input
input.value = '';
}
};
button.addEventListener('click', buttonClick);
})(document);