简体   繁体   English

分配给变量的 innerHTML 不能实时更新?

[英]innerHTML assigned to a variable cannot be updated live?

i'm trying to connect a div's text with a variable that changes value according to different buttons onclicks(with plain js), but cant figure out how to update the inner.HTML in a live manner,it just takes whatever value is on page load.我正在尝试将 div 的文本与根据不同按钮 onclicks(使用普通 js)更改值的变量连接起来,但无法弄清楚如何以实时方式更新 inner.HTML,它只需要页面上的任何值加载。 What am i doing wrong?我究竟做错了什么? Js student here. Js学生在这里。

 var counter1=0; var counter2=0; var counter3=0; var countertotal=counter1+counter2+counter3; document.getElementById("text").innerHTML= "Total" + "&nbsp" + parseInt(countertotal); function count1() { document.getElementById("button1").innerHTML =parseInt(counter1); counter1++; } function count2() { document.getElementById("button2").innerHTML =parseInt(counter2); counter2++; } function count3() { document.getElementById("button3").innerHTML =parseInt(counter3); counter3++; }
 <html> <body> <div id='text' style="font-size:50px"></div> <button style= "width:400px; height:150px; font-size:100px; display:block" id="button1" onclick="count1()"></button> <button style="width:400px;height:150px; font-size:100px; display:block" id="button2" onclick="count2()"></button> <button style="width:400px;height:150px;font-size:100px;display:block" id="button3" onclick="count3()"></button> </body> </html>

You should update the counter total after clicking on each button and then update the counter total innerHTML.您应该在单击每个按钮后更新计数器总数,然后更新计数器总数 innerHTML。 You only update the counter on a single button instance.您只更新单个按钮实例上的计数器。

For example on function count1例如在 function count1

function count1() {
   document.getElementById("button1").innerHTML =parseInt(counter1);
   counter1++;
   countertotal++;
   document.getElementById("text").innerHTML =  "Total" + "&nbsp" + 
   parseInt(countertotal);
}

Also the countertotal value doesn't update automatically because code is run from top to bottom and you pass values by value.此外,总价值不会自动更新,因为代码是从上到下运行的,并且您按值传递值。 For more info on this topic you can read here: value vs reference有关此主题的更多信息,您可以在此处阅读: 价值与参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM