我不知道我做错了什么。出于某种原因,我无法使用JS将此类添加到#otal-weight中。 CSS很好,因为我有硬编码并正在工作。总和也很完美。
/ **********这是我的HTML ************** /
<tr id="results">
<td>Grade (%)</td>
<td><input type="text" value="" id="final-grade" name="final-grade"></td>
<td><input type="text" value="100" id="total-weight" name="total-weight"><span><small> remaining (%)</small></span></td>
</tr>
/ ********这是我的JS *************** /
'use strict';
$(document).on('keyup', '.weight-value', function() {
// the sum of weight (%)
var sumWeight = 0;
var totalWeight = 0;
$('.weight-value').each(function(){
sumWeight += +$(this).val();
});// end of sum of weight (%)
// populate weigth remaining
totalWeight = $('#total-weight').val(100 - sumWeight);
if(totalWeight < 0) {
$('#total-weight').addClass('table-border');
}
});// end document .on keyup
答案 0 :(得分:1)
$('#total-weight').val(100 - sumWeight)
将设置元素的值并返回一个jQuery对象。所以你的情况不会起作用。
您也可以使用toggleClass()
,因为如果值为&gt; = 0
'use strict';
$(document).on('keyup', '.weight-value', function () {
// the sum of weight (%)
var sumWeight = 0;
var totalWeight = 0;
$('.weight-value').each(function () {
sumWeight += +$(this).val();
}); // end of sum of weight (%)
// populate weigth remaining
totalWeight = 100 - sumWeight;
$('#total-weight').val(totalWeight);
$('#total-weight').toggleClass('table-border', totalWeight < 0);
}); // end document .on keyup
演示:Fiddle