Javascript / Jquery - 多个更改(函数()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14642260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:28:20  来源:igfitidea点击:

Javascript / Jquery - Multiple on Change (function()

javascriptjquery

提问by Brandrally

I am kinda new to Jquery / JS and after a little help. I realise there hopefully is a much better way to do this, and any help would be greatly appreciated.

我对 Jquery / JS 有点陌生,在得到了一些帮助之后。我意识到希望有更好的方法来做到这一点,任何帮助将不胜感激。

I am building a form that can calculate a total. That is:

我正在构建一个可以计算总数的表单。那是:

'Cost' x '(1 + percent(%))' = 'total cost'

'成本' x '(1 + 百分比(%))' = '总成本'

I have it working nicely, though I want to make it so that if I change either the 'percent' field, or the 'cost' field then the total amountupdates. At the moment only if you update the 'cost' will the total update.

我让它工作得很好,但我想这样做,如果我更改“百分比”字段或“成本”字段,则总金额会更新。目前只有当你更新'成本'时,总更新

Hope that makes sense. Code is below.

希望这是有道理的。代码如下。

$(document).ready(function(){

$("#cost").change(function() { 
var findprofit = parseFloat($("#cost").val());
var profit = (findprofit*.01)
var margin = parseFloat($("#percentage").val());
var total = profit*margin;
$(".profit_1_1").html(total);
var totalprofit = (total + findprofit);
$("#total").val(totalprofit);
});

<input type="text" name="cost" id="cost"  />
<input type="text" name="percentage" id="cost" percentage />
<input type="text" name="total" id="total" readonly />

回答by James Donnelly

$("#cost, #percent").change(function() { 
    ...
});

Should do the trick.

应该做的伎俩。

Edit: You'll need to give your percent input an id of "percent". Two elements may not have the same ID.

编辑:你需要给你的百分比输入一个“百分比”的id。两个元素可能不具有相同的 ID。

<input type="text" name="cost" id="cost"  />
<input type="text" name="percentage" id="percent" percentage />
<input type="text" name="total" id="total" readonly />

Also I'm not sure what that "percentage" is at the end of the input. Percentage isn't a valid attribute.

另外,我不确定输入末尾的“百分比”是多少。百分比不是有效的属性。