简体   繁体   English

更新函数中的全局js变量并将更新发送到HTML文档

[英]Updating global js variable within function and sending updated to HTML document

I am having a really hard time updating a global variable and sending the updated to HTML. 我很难更新全局变量并将更新发送到HTML。

I have the following in HTML: 我在HTML中具有以下内容:

We found <script type="text/javascript">
var $mainCount; 
document.write($mainCount); </script> places for you!

In Javascript: 用Javascript:

   var $mainCount = 3; //Global variable

   if (1 = 1) {
   test();
   }

   function test() {
   $mainCount;

   for (var p = 0; p < 10; p++){

   $mainCount = p;
}
}

However, the HTML page does not update the number to 9, and still writes 3 as the global variable was declared as first 但是,HTML页面不会将数字更新为9,并且由于全局变量被声明为first,因此仍写3。

There is no way to bind HTML to a JavaScript variable. 无法将HTML绑定到JavaScript变量。

If you want to update the HTML, then you need to use DOM manipulation to do it. 如果要更新HTML,则需要使用DOM操作来完成。

So as we stated in comments you will have to use javascript for it. 因此,正如我们在评论中所述,您将必须使用javascript。

var $globalVariable = 3;

(function() {
  console.log('asa');
  $globalVariable = 9;
  document.getElementById("field").innerHTML = $globalVariable;
})();

Take a look at this jsfiddle code. 看一下这个jsfiddle代码。

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

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