基本上尝试将变量添加到一起,然后将它们传递给最终变量
//-- answers --//
var groupA1 = 0;
var groupA2 = 0;
var groupA3 = 0;
var answerQuestion1 = 0;
testButton.on('click', function () {
answerQuestion1 = ((groupA1).val) + ((groupA2).val) + ((groupA3).val);
console.log("I am being clicked");
console.log(answerQuestion1);
console.log(groupA1);
console.log(groupA2);
console.log(groupA3);
});
任何人都知道为什么'answerQuestion1'正在安慰'NaN'?
干杯
答案 0 :(得分:0)
在添加之前使用parseInt,以便它不会连接为字符串
//-- answers --//
var groupA1 = 0;
var groupA2 = 0;
var groupA3 = 0;
var answerQuestion1 = 0;
$('button').on('click', function () {
answerQuestion1 = parseInt($('[name="groupA1"]').val()) + parseInt($('[name="groupA2"]').val()) + parseInt($('[name="groupA3"]').val());
console.log("I am being clicked");
console.log(answerQuestion1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="3" name="groupA1">
<input type="number" value="2" name="groupA2">
<input type="number" value="1" name="groupA3">
<button>Compute</button>
答案 1 :(得分:0)
变量未与.val
一起使用,并使用parseInt
进行计算,否则使用“+”运算符进行字符串连接。
var groupA1 = 0;
var groupA2 = 0;
var groupA3 = 0;
var answerQuestion1 = 0;
$('#testButton').on('click', function() {
answerQuestion1 = parseInt(groupA1) + parseInt(groupA2) + parseInt(groupA3);
console.log("I am being clicked");
console.log(answerQuestion1);
console.log(groupA1);
console.log(groupA2);
console.log(groupA3);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' id='testButton'>