0

我正在尝试随着数据输入的变化(由用户)更改饼图的值。

对于上下文,我目前有 4 个参数,称为 Ativo(其中 5 个)、配额(每个设置为 20%、100% 除以 5 个 ativos)、Perda 潜力(每个设置为 0,最大值为 100%)和 Perda (最初设置为 0,但将是累积的)。随着 perda 潜力的增加,配额将以 1:5 的比例减少,反之亦然(例如,如果 perda 潜力 = 20%,那么配额将为 16%。Perda 潜力增加 1% = 配额减少 0.2% )

我现在想从输入的更新值中获取原始配额 (20%) 和新配额之间的差异(以前面的示例为例,这将是 20% - 16% = 4%)并保存在Perda 变量。然后这个 perda 将作为饼图添加,而新配额为 16% 的 Ativo 将在饼图上更新(例如,如果我们想更改第一个 Ativo 并放置前面示例中的值,我们将从 5 个饼片中的 1 个 20% 变为 6 个饼片,一个新配额为 16%,另一个 perda 为 4%,另外 4 个饼片将保持 20%,因为它们没有更改)。此 perda 值将是累积的,因此如果任何其他配额发生更改,perda 将对这些值求和。

代码正在更新图表(增加perda potencial%会减少quota%并在按下按钮后改变饼片的值),但是为perda添加的饼片基本上是最后改变的配额的值而不是两者之间的差异原配额和新配额。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

</head>

<body>
    <div>


        <div class="table">
            <form id="form">
                <div class="tr">
                    <div class="td">Ativo </div>
                    <div class="td">Quota % </div>
                    <div class="td">Perda Potencial % </div>
                </div>

                <form id="ativo1test" value="teste"></form>
                <div class="tr">
                    <div class="td"><input type="text" size="5" value="TSLA" class="stock" id="ativo1"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota1"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda1" /> </div>
                </div>
                <div class="tr">
                    <div class="td"><input type="text" size="5" value="AAPL" class="stock" id="ativo2"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota2"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda2" /> </div>
                </div>
                <div class="tr">
                    <div class="td"><input type="text" size="5" value="MSFT" class="stock" id="ativo3"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota3"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda3" /> </div>
                </div>
                <div class="tr">
                    <div class="td"><input type="text" size="5" value="EURUSD" class="stock" id="ativo4" /> </div>
                    <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota4" /> </div>
                    <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda4" /> </div>
                </div>
                <div class="tr">
                    <div class="td"><input type="text" size="5" value="BITCOIN" class="stock" id="ativo5"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota5"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda5" /></div>
                </div>
                <button type="button" onclick="drawChart();">Desenhar Gráfico</button>
            </form>

        </div>
        <div id="piechart" style="width: 900px; height: 500px;"></div>

        <script>
            ////////////////////////////////////////////////////////////////////////////////////
            //Get all the values for each stock input and the quota variation (as "Perda potencial" increases, Quota decreases by a ratio of 1:5 and vice-versa)

            ////////////////////////////////////////////////////////////////////////////////////
            //Create arrays so that we can use a for loop (not sure if this would work?) and update the values as the input is changed by the user


            ////////////////////////////////////////////////////////////////////////////////////

            document.querySelector(".table").addEventListener("input", function (e) {
                const tgt = e.target;
                if (tgt.classList.contains("perda")) {
                    perda = tgt.closest(".tr").querySelector(".quota").value =
                        20 - tgt.value * 0.2;

                    // quota * perda potencial; var = quota * +- perda potencial / 100
                    //quota - var;
                    //let var = perda/risco potencial
                    //console.log(20 - perda);

                    //isto teria que atualizar sempre que a perda potencial % aumenta ou diminui. Neste momento, apenas faz a soma, nao retira o valor quando perda potencial % diminui e a quota aumenta
                }
            });

            ////////////////////////////////////////////////////////////////////////////////////
            //Create a "Perda" (Loss) variable that contains the inverse of "Quota". Example: If "Perda potencial" is at 20%, then our "Quota" will be at 16% and our "Perda" would be at 4% (20-16 = 4; original quota - updated quota = perda). This variable should be cumulative so that it will sum up the values for each alteration on the "Quota %" of each "Ativo" (Stock);

            ////////////////////////////////////////////////////////////////////////////////////
            //Load google chart graphs

            google.charts.load("current", { packages: ["corechart"] });
            google.charts.setOnLoadCallback(drawChart);

            ////////////////////////////////////////////////////////////////////////////////////
            //Function that will be passed by the "Desenhar grafico" button so that everytime the user clicks the button, it takes the new input values and updates the pie chart
            let perda;

            function drawChart() {

                let ativo1 = document.getElementById("ativo1").value;
                let ativo2 = document.getElementById("ativo2").value;
                let ativo3 = document.getElementById("ativo3").value;
                let ativo4 = document.getElementById("ativo4").value;
                let ativo5 = document.getElementById("ativo5").value;
                let ativosArray = [ativo1, ativo2, ativo3, ativo4, ativo5];

                let quota1 = document.getElementById("quota1").value;
                let quota2 = document.getElementById("quota2").value;
                let quota3 = document.getElementById("quota3").value;
                let quota4 = document.getElementById("quota4").value;
                let quota5 = document.getElementById("quota5").value;
                let quotaArray = [quota1, quota2, quota3, quota4, quota5];

                for (let i = 0; i < quotaArray.length; i++) {
                    perda == quotaArray[i].value;

                };

                console.log(perda)

                var data = new google.visualization.DataTable();
                data.addColumn("string", "Ativo");
                data.addColumn("number", "Quota");
                data.addRows([
                    [ativo1, parseFloat(quota1)],
                    [ativo2, parseFloat(quota2)],
                    [ativo3, parseFloat(quota3)],
                    [ativo4, parseFloat(quota4)],
                    [ativo5, parseFloat(quota5)],
                    ["Perda", parseFloat(perda)],
                ]);
                var options = {
                    title: "Calculadora",
                    pieHole: 0.3,
                    pieSliceText: 'value',
                    is3D: true,

                };

                var chart = new google.visualization.PieChart(
                    document.getElementById("piechart")
                );

                chart.draw(data, options);

                console.log(ativo1)
                console.log(quota1);

            }

            ////////////////////////////////////////////////////////////////////////////////////
        </script>
</body>


<style>
    .td {
        display: inline-block;
        width: 120px;
        text-align: right;
    }
</style>

</html>

4

1 回答 1

0

我认为问题在于计算perda. 你的问题太长了,所以我可能误解了你的意图。随时澄清。

perda == quotaArray[i].value;

...只会评估为truefalse作为表达式。也许你的意思是使用=,这意味着分配?

无论如何,这并不能解决您的问题。我想你想要一个叫做Perda- 的100馅饼片sum of all others。所以,你可以像这样评估它

let sum = 0.0;
for (let i = 0; i < quotaArray.length; i++) {
  sum += parseFloat(quotaArray[i]);
};
perda = 100.0 - sum;

具有此修改的工作片段。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

</head>

<body>
  <div>


    <div class="table">
      <form id="form">
        <div class="tr">
          <div class="td">Ativo </div>
          <div class="td">Quota % </div>
          <div class="td">Perda Potencial % </div>
        </div>

        <form id="ativo1test" value="teste"></form>
        <div class="tr">
          <div class="td"><input type="text" size="5" value="TSLA" class="stock" id="ativo1" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota1" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda1" /> </div>
        </div>
        <div class="tr">
          <div class="td"><input type="text" size="5" value="AAPL" class="stock" id="ativo2" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota2" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda2" /> </div>
        </div>
        <div class="tr">
          <div class="td"><input type="text" size="5" value="MSFT" class="stock" id="ativo3" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota3" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda3" /> </div>
        </div>
        <div class="tr">
          <div class="td"><input type="text" size="5" value="EURUSD" class="stock" id="ativo4" /> </div>
          <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota4" /> </div>
          <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda4" /> </div>
        </div>
        <div class="tr">
          <div class="td"><input type="text" size="5" value="BITCOIN" class="stock" id="ativo5" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota5" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda5" /></div>
        </div>
        <button type="button" onclick="drawChart();">Desenhar Gráfico</button>
      </form>

    </div>
    <div id="piechart" style="width: 900px; height: 500px;"></div>

    <script>
      ////////////////////////////////////////////////////////////////////////////////////
      //Get all the values for each stock input and the quota variation (as "Perda potencial" increases, Quota decreases by a ratio of 1:5 and vice-versa)

      ////////////////////////////////////////////////////////////////////////////////////
      //Create arrays so that we can use a for loop (not sure if this would work?) and update the values as the input is changed by the user


      ////////////////////////////////////////////////////////////////////////////////////

      document.querySelector(".table").addEventListener("input", function(e) {
        const tgt = e.target;
        if (tgt.classList.contains("perda")) {
          perda = tgt.closest(".tr").querySelector(".quota").value =
            20 - tgt.value * 0.2;

          // quota * perda potencial; var = quota * +- perda potencial / 100
          //quota - var;
          //let var = perda/risco potencial
          //console.log(20 - perda);

          //isto teria que atualizar sempre que a perda potencial % aumenta ou diminui. Neste momento, apenas faz a soma, nao retira o valor quando perda potencial % diminui e a quota aumenta
        }
      });

      ////////////////////////////////////////////////////////////////////////////////////
      //Create a "Perda" (Loss) variable that contains the inverse of "Quota". Example: If "Perda potencial" is at 20%, then our "Quota" will be at 16% and our "Perda" would be at 4% (20-16 = 4; original quota - updated quota = perda). This variable should be cumulative so that it will sum up the values for each alteration on the "Quota %" of each "Ativo" (Stock);

      ////////////////////////////////////////////////////////////////////////////////////
      //Load google chart graphs

      google.charts.load("current", {
        packages: ["corechart"]
      });
      google.charts.setOnLoadCallback(drawChart);

      ////////////////////////////////////////////////////////////////////////////////////
      //Function that will be passed by the "Desenhar grafico" button so that everytime the user clicks the button, it takes the new input values and updates the pie chart
      let perda;

      function drawChart() {

        let ativo1 = document.getElementById("ativo1").value;
        let ativo2 = document.getElementById("ativo2").value;
        let ativo3 = document.getElementById("ativo3").value;
        let ativo4 = document.getElementById("ativo4").value;
        let ativo5 = document.getElementById("ativo5").value;
        let ativosArray = [ativo1, ativo2, ativo3, ativo4, ativo5];

        let quota1 = document.getElementById("quota1").value;
        let quota2 = document.getElementById("quota2").value;
        let quota3 = document.getElementById("quota3").value;
        let quota4 = document.getElementById("quota4").value;
        let quota5 = document.getElementById("quota5").value;
        let quotaArray = [quota1, quota2, quota3, quota4, quota5];

        let sum = 0.0;
        for (let i = 0; i < quotaArray.length; i++) {
          sum += parseFloat(quotaArray[i]);
        };
        perda = 100.0 - sum;

        console.log(perda)

        var data = new google.visualization.DataTable();
        data.addColumn("string", "Ativo");
        data.addColumn("number", "Quota");
        data.addRows([
          [ativo1, parseFloat(quota1)],
          [ativo2, parseFloat(quota2)],
          [ativo3, parseFloat(quota3)],
          [ativo4, parseFloat(quota4)],
          [ativo5, parseFloat(quota5)],
          ["Perda", perda],
        ]);
        var options = {
          title: "Calculadora",
          pieHole: 0.3,
          pieSliceText: 'value',
          is3D: true,

        };

        var chart = new google.visualization.PieChart(
          document.getElementById("piechart")
        );

        chart.draw(data, options);

        console.log(ativo1)
        console.log(quota1);

      }

      ////////////////////////////////////////////////////////////////////////////////////
    </script>
</body>


<style>
  .td {
    display: inline-block;
    width: 120px;
    text-align: right;
  }
</style>

</html>

我将如何使用 for 循环来简化相同代码的示例。此外,充分利用堆栈片段来减少读者的混乱程度。当然,您可以考虑使用其他 Array 方法,例如reduce, forEach

////////////////////////////////////////////////////////////////////////////////////
//Get all the values for each stock input and the quota variation (as "Perda potencial" increases, Quota decreases by a ratio of 1:5 and vice-versa)

////////////////////////////////////////////////////////////////////////////////////
//Create arrays so that we can use a for loop (not sure if this would work?) and update the values as the input is changed by the user


////////////////////////////////////////////////////////////////////////////////////

document.querySelector(".table").addEventListener("input", function(e) {
  const tgt = e.target;
  if (tgt.classList.contains("perda")) {
    perda = tgt.closest(".tr").querySelector(".quota").value =
      20 - tgt.value * 0.2;

    // quota * perda potencial; var = quota * +- perda potencial / 100
    //quota - var;
    //let var = perda/risco potencial
    //console.log(20 - perda);

    //isto teria que atualizar sempre que a perda potencial % aumenta ou diminui. Neste momento, apenas faz a soma, nao retira o valor quando perda potencial % diminui e a quota aumenta
  }
});

////////////////////////////////////////////////////////////////////////////////////
//Create a "Perda" (Loss) variable that contains the inverse of "Quota". Example: If "Perda potencial" is at 20%, then our "Quota" will be at 16% and our "Perda" would be at 4% (20-16 = 4; original quota - updated quota = perda). This variable should be cumulative so that it will sum up the values for each alteration on the "Quota %" of each "Ativo" (Stock);

////////////////////////////////////////////////////////////////////////////////////
//Load google chart graphs

google.charts.load("current", {
  packages: ["corechart"]
});
google.charts.setOnLoadCallback(drawChart);

////////////////////////////////////////////////////////////////////////////////////
//Function that will be passed by the "Desenhar grafico" button so that everytime the user clicks the button, it takes the new input values and updates the pie chart
let perda;

function drawChart() {
  const slices = [];
  for (let i = 1; i <= 5; i++) {
    slices.push({
      ativo: document.getElementById(`ativo${i}`).value,
      quota: parseFloat(document.getElementById(`quota${i}`).value)
    })
  }

  let sum = 0.0;
  for (let i = 0; i < slices.length; i++) {
    sum += slices[i].quota;
  };
  perda = 100.0 - sum;

  console.log(perda)

  var data = new google.visualization.DataTable();
  data.addColumn("string", "Ativo");
  data.addColumn("number", "Quota");
  data.addRows([
    ...slices.map(slice => ([slice.ativo, slice.quota])),
    ["Perda", perda],
  ]);
  var options = {
    title: "Calculadora",
    pieHole: 0.3,
    pieSliceText: 'value',
    is3D: true,

  };

  var chart = new google.visualization.PieChart(
    document.getElementById("piechart")
  );

  chart.draw(data, options);

}
.td {
  display: inline-block;
  width: 120px;
  text-align: right;
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<div>
  <div class="table">
    <form id="form">
      <div class="tr">
        <div class="td">Ativo </div>
        <div class="td">Quota % </div>
        <div class="td">Perda Potencial % </div>
      </div>

      <form id="ativo1test" value="teste"></form>
      <div class="tr">
        <div class="td"><input type="text" size="5" value="TSLA" class="stock" id="ativo1" onchange="drawChart();" /> </div>
        <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota1" onchange="drawChart();" /> </div>
        <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda1" /> </div>
      </div>
      <div class="tr">
        <div class="td"><input type="text" size="5" value="AAPL" class="stock" id="ativo2" onchange="drawChart();" /> </div>
        <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota2" onchange="drawChart();" /> </div>
        <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda2" /> </div>
      </div>
      <div class="tr">
        <div class="td"><input type="text" size="5" value="MSFT" class="stock" id="ativo3" onchange="drawChart();" /> </div>
        <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota3" onchange="drawChart();" /> </div>
        <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda3" /> </div>
      </div>
      <div class="tr">
        <div class="td"><input type="text" size="5" value="EURUSD" class="stock" id="ativo4" /> </div>
        <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota4" /> </div>
        <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda4" /> </div>
      </div>
      <div class="tr">
        <div class="td"><input type="text" size="5" value="BITCOIN" class="stock" id="ativo5" onchange="drawChart();" /> </div>
        <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota5" onchange="drawChart();" /> </div>
        <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda5" /></div>
      </div>
      <button type="button" onclick="drawChart();">Desenhar Gráfico</button>
    </form>

  </div>
  <div id="piechart" style="width: 900px; height: 500px;"></div>

于 2021-09-11T21:24:19.220 回答