gpt4 book ai didi

javascript - 如果 var < 0 jquery 添加一个类

转载 作者:行者123 更新时间:2023-12-03 10:25:54 25 4
gpt4 key购买 nike

我不知道我做错了什么。由于某种原因,我无法使用 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) 将设置元素的值并返回一个 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

关于javascript - 如果 var < 0 jquery 添加一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29404363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com