【问题标题】:Why can't I change a variable's textContent's atribute in an if-statement?为什么我不能在 if 语句中更改变量的 textContent 属性?
【发布时间】:2022-01-11 18:01:19
【问题描述】:

为什么变量 span_perc 的颜色没有变为红色,即使我知道我刚刚将它的 textContent 更新为“-28.86%”?

如果我将 span_perc.textContent 记录到控制台,它会说这是一个即使这不是真的,因为它可以将其更改为绿色并且我可以在网站上看到它。


    <div class="col-12 xl:col-6">
        <div class="card">
            <h5>Total Profits</h5>
            <span id="profits_perc"></span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <span id="profits_money"></span>
            <Chart type="line" :data="lineData" />
        </div>
    </div>
    </div>
</template>

<script>
import ProductService from '../service/ProductService';
import axios from 'axios';

window.onload = dostuff;

function dostuff() {
    var span_perc = document.getElementById("profits_perc");
    var span_money = document.getElementById("profits_money");
    axios.get('http://localhost:8000/').then(response => {span_perc.textContent = response.data[2].profits_perc});
    axios.get('http://localhost:8000/').then(response => {span_money.textContent = response.data[2].profits_cash});
    if (span_perc.textContent == '-28.86%') {
        span_perc.setAttribute("style", "color:red")
    } else {
        span_perc.setAttribute("style", "color:green")
    }
}

【问题讨论】:

  • 如果你真的使用 Vue.js 那么使用响应式来动态改变样式、类和其他人员。

标签: javascript html vue.js


【解决方案1】:

这是因为值在 XHR 调用中以异步方式更改,如果您在 then 块中包含 if 条件,它应该可以工作:

axios.get('http://localhost:8000/').then(response => {
span_perc.textContent = response.data[2].profits_perc;
if (span_perc.textContent == '-28.86%') {
        span_perc.setAttribute("style", "color:red")
    } else {
        span_perc.setAttribute("style", "color:green")
    }
});

【讨论】:

    【解决方案2】:

    尝试在异步调用中执行更改。

    为什么异步工作的本质是,当我们等待承诺解决为某些数据或错误时,其余代码将继续执行。

    function dostuff() {
          var span_perc = document.getElementById("profits_perc");
          var span_money = document.getElementById("profits_money");
          axios.get("http://localhost:8000/").then((response) => {
            span_perc.textContent = response.data[2].profits_perc;
            if (span_perc.textContent == "-28.86%") {
                span_perc.setAttribute("style", "color:red");
              } else {
                span_perc.setAttribute("style", "color:green");
              }
          });
          axios.get("http://localhost:8000/").then((response) => {
            span_money.textContent = response.data[2].profits_cash;
          });
          
        }
    

    【讨论】:

      猜你喜欢
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多