添加一个 class 如果 var < 0 jquery
Add a class if var < 0 jquery
我不知道我做错了什么。出于某种原因,我无法将此 class 添加到带有 JS 的 #total-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
$('#total-weight').val(100 - sumWeight)
将设置元素的值和 return 一个 jQuery 对象。所以你的条件不行。
您可能还想使用 toggleClass()
,因为如果值为 >=0
,您想要删除 class
'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
我不知道我做错了什么。出于某种原因,我无法将此 class 添加到带有 JS 的 #total-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
$('#total-weight').val(100 - sumWeight)
将设置元素的值和 return 一个 jQuery 对象。所以你的条件不行。
您可能还想使用 toggleClass()
,因为如果值为 >=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