javascript 全局变量更新不工作

javascript global variable update not working

我无法使基本功能正常工作 - 更新函数中全局变量的内容。

这里是过于简化的代码示例:

<html>

  <head>
    <script>
      window.mytestip = "Var set as global"; 
      var ConditionVar = 1;

      if (ConditionVar == 1)(function() {
      mytestip = "Var set to Yes";
      });
      else(function() {
        mytestip = "Var set to No";
      });

    </script>
  </head>

  <body>
    <p> <span id=mytest>-</span> </p>
    <script>
      document.getElementById('mytest').innerHTML = window.mytestip;

    </script>
  </body>

</html>

为什么mytestip没有更新?

这是一个 jfiddle:https://jsfiddle.net/4bu8gp9f/

分辨率:

添加 () 实际上解决了出现的代码问题。 但是我的代码是嵌套的,我无法使用它。

相反,我通过设置本地存储变量解决了这个问题,稍后从本地存储中取回它:

函数中: localStorage.setItem("LocalIp", 我的测试);

稍后在代码中: 我的测试 = localStorage.getItem("LocalIp");

谢谢大家!

你应该使用:

if (ConditionVar == 1) {
    mytestip = "Var set to Yes";
} else {
    mytestip = "Var set to No";
}

我认为你的 if else statement 是错误的。

所以我尝试这样做。

<html>

  <head>
    <script>
      window.mytestip = "Var set as global";
      var RTCPeerConnection = window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

      if (RTCPeerConnection){
        window.mytestip = "Var set to Yes";
      }
      else{
        window.mytestip = "Var set to No";
      }

    </script>
  </head>

  <body>
    <p> <span id=mytest>-</span> </p>
    <script>
      document.getElementById('mytest').innerHTML = window.mytestip;

    </script>
  </body>

</html>

正如 Daniel 和 Paul 在评论中所说的那样,试试这个代码:

if (RTCPeerConnection) {
    window.mytestip = "Var set to Yes";
 }else 
    window.mytestip = "Var set to No";
 }

并且不要忘记在您的 span id 参数上引用

所以,我相信您在 ifs 中使用函数是有充分理由的,所以如果是这种情况,您只是错过了内联函数之后的“()”:

if (ConditionVar == 1) {
    (function() {
        mytestip = "Var set to Yes";
    })();
} else {
    (function() {
        mytestip = "Var set to No";
    })();
}

我添加了括号来组织代码(并建议始终这样做)

如果不是这样,请遵循其他建议的答案。

分辨率:

添加 () 实际上解决了出现的代码问题。但是我的代码是嵌套的,我无法使用它。

相反,我通过设置本地存储变量解决了这个问题,并稍后从本地存储中检索它:

函数中: localStorage.setItem("LocalIp", 我的测试);

稍后在代码中: 我的测试 = localStorage.getItem("LocalIp");

谢谢大家!