[英]Javascript - Why can't I update the textContent of an h3 with my conditional statement?
[英]Why can't I change a variable's textContent's atribute in an if-statement?
即使我知道我刚刚将它的 textContent 更新为“-28.86%”,为什么变量 span_perc 的颜色不会变为红色?
如果我将 span_perc.textContent 记录到控制台,它会说这是一个即使这不是真的,因为它可以将其更改为绿色并且我可以在网站上看到它。
<div class="col-12 xl:col-6">
<div class="card">
<h5>Total Profits</h5>
<span id="profits_perc"></span>
<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")
}
}
这是因为值在 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")
}
});
尝试在异步调用中执行更改。
为什么异步工作的本质是,当我们等待 promise 解析为某些数据或错误时,代码的 rest 将继续执行。
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;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.