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

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

问题描述:

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

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

文本区号:

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

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

passing value to var and adding it to another var

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

将var c传递给div id测试

passing var c to div id test

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

html作为测试ID

html for test id

<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 ?

如果要在每次输入内容时进行更新,则需要一个事件处理程序:

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