I think this is what you are trying to do. Checkout this fiddle. You can always extend this for other color
elements.
one js file for calculations
-
24-09-2022 - |
سؤال
i have a js file (which utilises the jquery framework) that is a simple equation to calculate corresponding values.
JS FILE (sample):
var colorOneRed = parseFloat($('#colorOneRed').text()); ...
var totalRed = (parseFloat(colorOneRed) + parseFloat(colorTwoRed) ...
$('#totalColorRed').text(totalRed); ...
I have the same exact equation multiple times, only the color changes. So the same equation is used for green var colorGreen
, blue, purple, etc.
My question is can I write just the one equation to encompass all the variables and #id's
instead writing the same equation over and over.
I tried the id^='totalcolor'
method for example, but it will only calculate the one variable. So what I mean is, if #colorOneRed
has a value of 40
but #colorOneGreen
has a value of 60
it will only calculate the one value for all using the id^=colorOne
method.
I'm not sure its even possible but i'm hoping to have one equation that will be able to have a calculation for all the greens
and one for all the blues
and so on.
Thanks in advance for any help.
المحلول
نصائح أخرى
Put the calculation in one function:
function calc(displayElt, color){
var total=parseFloat($('#colorOne'+color).text()) + parseFloat($('#colorTwo'+color).text())+..
$('#'+displayElt).text(total);
}
calc(totalColorRed,Red);
Wrap your code in a function where you pass in the required DOM elements to perform the calculation:
function calculate(colorOneElement, totalElement) {
var colorOne = parseFloat($(colorOneElement).text()); ...
var total = (parseFloat(colorOneRed) + parseFloat(colorTwoRed) ...
$(totalElemenet).text(totalRed); ...
}
The use as follows:
calculate(document.getElementById("colorOneRed"),
document.getElementById("totalOneRed"));
calculate(document.getElementById("colorOneGreen"),
document.getElementById("totalOneGreen"));
etc ...