【发布时间】:2018-12-04 03:38:29
【问题描述】:
我无法让基本工作正常工作 - 更新函数中全局变量的内容。
所以这里是过度简化的代码示例:
<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", mytestip );
稍后在代码中: mytestip = localStorage.getItem("LocalIp");
谢谢大家!
【问题讨论】:
-
else和if不是函数,不带回调函数。它们是作用域块, -
if (RTCPeerConnection){ window.mytestip = "Var 设置为 Yes"; } else { window.mytestip = "变量设置为否"; }
-
如果你要使用
IIFEdeveloper.mozilla.org/en-US/docs/Glossary/IIFE,别忘了执行它们。if (ConditionVar == 1)(function() { mytestip = "Var set to Yes"; })();注意额外的()然后结束。 -
下面的所有答案都去掉了 function(){} 部分 - 问题是更新在函数内不起作用
-
感谢基思,额外的 () 确实有所作为。让我看看它如何影响完整的代码
标签: javascript variables global