【发布时间】:2018-04-11 17:41:08
【问题描述】:
我正在尝试制作一个带有输入元素的小型计算器。我已经构建了一个加号按钮,用于在最后一个输入字段之后插入一个新的输入字段。它正在工作。
现在我正在尝试对每个输入字段求和。但我在控制台中得到 undefined 。我不知道出了什么问题,因为我是编程新手。 我尝试使用 .input-time 类获取输入字段的值,然后将其放入数组中。然后做一个 for 循环来对它们求和。
编辑:
非常感谢您的帮助。我使用了@Yoiki 的代码,因为它是一种新的、简单的方法。我编辑了剪断的代码。它现在正在工作。
$(function() {
// ADDING NEW INPUT FIELD
$('.button-plus').on('click', function(event) {
event.preventDefault();
let inPut = $('.input-time');
let inPutArr = jQuery.makeArray( inPut );
// console.log(inPutArr);
let lastInPut = inPutArr[inPutArr.length-1]; // get last elem of array
$(lastInPut).addClass('lastone'); // add class to it
$('.lastone').after('<input type=\"text\" class=\"input-time\">');
$('.lastone').delay(10).removeClass('lastone');
});
/* OLD CODE - NOT WORKING!!!
$('#button-calc').on('click', function(event) {
event.preventDefault();
let inPutV = $('.input-time').val();
let inPutVal = jQuery.makeArray( inPutV );
for (var i = 0; i < inPutVal.length; i++) {
var sum = sum + inPutVal[i];
}
console.log(sum);
});
*/
// NEW CODE - WORKING!!!
$('#button-calc').on('click', function(event) {
event.preventDefault();
let sum = 0;
$('.input-time').each (function () {
sum += +$(this).val();
});
console.log (sum);
});
});
/* IGNORE THE STYLE ;) */
input {
width: 160px;
height: 20px;
padding: 10px 20px 10px 20px;
border: none;
border-radius: 20px;
font-size: 15px;
display: block;
margin-bottom: 10px;
}
.container {
background-color: #dde4fe;
padding: 20px;
width: 200px;
margin-right: 20px;
margin-left: auto;
margin-right: auto;
margin-top: 100px;
}
.button-plus {
width: 40px;
height: 40px;
background-color: #9aadfd;
color: #fff;
cursor: pointer;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
border-radius: 20px;
display: flex;
align-items: center;
justify-content: center;
}
#button-calc {
width: 200px;
height: 40px;
background-color: #5677fc;
color: #fff;
cursor: pointer;
margin-top: 20px;
margin-bottom: 0;
}
.btn-plus {
width: 20px;
margin-left: auto;
margin-right: auto;
height: 5px;
background-color: #5677fc;
border-radius: 5px;
position: absolute;
}
.plus-1 {
transition: 0.5s;
transform: rotate(0deg);
}
.plus-2 {
transition: 0.5s;
transform: rotate(90deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="container">
<div class="container-inner">
<input type="text" class="input-time">
<input type="text" class="input-time">
<div class="button-plus">
<div class="btn-plus plus-1"></div>
<div class="btn-plus plus-2"></div>
</div>
<input type="submit" id="button-calc" value="Calculate">
</div>
</section>
【问题讨论】:
标签: javascript jquery html input calculator