如何在不刷新页面的情况下更新 html 中的 javascript 变量值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17900348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:02:39  来源:igfitidea点击:

How to update javascript variable value in html without a page refresh

javascripthtml

提问by acr

I am collecting a text area value(number in decimal ) using its id to a javascript variable, adding another variable value (number in decimal), and displaying the result in same html page

我正在收集一个文本区域值(十进制数字),使用它的 id 到一个 javascript 变量,添加另一个变量值(十进制数字),并在同一个 html 页面中显示结果

text area code:

文本区代码:

<div class="input-resp"><span><input  class="textbox" id="num" name="count" type="text" size="5" maxlength="3"  value="" /></span></div>

passing value to var and adding it to another var

将值传递给 var 并将其添加到另一个 var

var a = document.getElementById('num').value;
var b = 1000;
var c = parseFloat(a) + parseFloat(b); 

passing var c to div id test

将 var c 传递给 div id 测试

document.getElementById("test").innerHTML = c;

html for test id

测试 id 的 html

<div id="test"></div>

But here, whenever I am updating the text area with new number, the final output is not updating instantly.I have refresh the page manually to get new value. Is there anyway I update the value without a page refresh ?

但是在这里,每当我用新数字更新文本区域时,最终输出不会立即更新。我手动刷新页面以获得新值。无论如何我在没有页面刷新的情况下更新值?

采纳答案by adeneo

If it's going to update whenever you type into the input, you need an event handler:

如果每次输入输入时它都会更新,则需要一个事件处理程序:

document.getElementById('num').onkeyup = function() {
    var a = 1000 + parseFloat(this.value);
    document.getElementById("test").innerHTML = a || 0;
}

FIDDLE

小提琴