我有两个输入,借方和贷方,单击按钮即可更新名为“借方”的数组。借方增加正值,贷方增加负值。
然后,我将数组中的值求和到变量“totalDebits”,并使用该变量更新“totalOutput”的 html。
我的目标是单击图标 [-],当删除借项时,从数组中减去该值并更新总输出。当信用被删除时,它应该添加从数组中删除该负值。
我尝试使用 splice.() 和 .inArray() 方法,但由于某种原因,当我删除借方时,它会清空整个数组。
这是我尝试过的代码片段,以及 jsFiddle,以便您可以看到问题。
//CLOSE BUT NO CIGAR, -
$(document).ready(function()
{
$(document).on('click','.fa-minus-square',
function()
{
var thisVal = Number($(this).parent().attr('value'));
if ($(this).parent().hasClass('debitItem')){
debits.splice($.inArray(thisVal, debits) ,1 );
$(this).parent().remove();
console.log(debits);
} else if ($(this).parent().hasClass('creditItem')) {
debits.splice($.inArray(-thisVal, debits) ,1 );
$(this).parent().remove();
};
}
);
});
https://jsfiddle.net/agraymd/pbtof136/4/
在查看控制台时,它似乎做了我想要的事情,但是在删除了单击的借记的值之后,它只是不断删除,直到数组为空。
我可以自己更新totalOutput,但我删除了这部分代码,因为它没有正确更新数组。
我希望我的解释清楚并使用正确的术语。我还是个新手:)
<小时/>
这是一个新的 fiddle ,我将借方或贷方的反向值添加到借方数组中,而不是删除它。不过我觉得去掉它会更好。 https://jsfiddle.net/agraymd/pbtof136/
<小时/>最佳答案
在设置整个匹配集之前,您需要取消绑定(bind)现有的 onclick 事件处理程序。就好像按钮被再次点击了 n 次(n = 此后添加的条目数),但实际上该函数被再次调用了 n 次,因为它被分配给了 n 次点击事件。
更改此:
$(document).on('click','.fa-minus-square',
function()
{
...
});
至:
$('.fa-minus-square').unbind().click(function()
{
...
});
我已在this fiddle中进行了适当的更改.
关于javascript - 从数组中删除值,使用新数组总计更新 html,如果没有总计,则更新 '$',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36538241/