【发布时间】:2018-02-06 15:30:46
【问题描述】:
我试图让它在用户单击演示部分时每次切换标志值。
我的印象是静态变量是 myFunction.flag,每次更改时它都会在整个页面中保持不变...
<!DOCTYPE html>
<html>
<body>
<p>Search a string for "w3Schools", and display the position of the match:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools!";
var n = str.search(/w3Schools/i);
myFunction.flag = 1;
if(myFunction.flag){
document.getElementById("demo").innerHTML = myFunction.flag;
myFunction.flag = 0;
} else {
document.getElementById("demo").innerHTML = myFunction.flag;
myFunction.flag = 1;
}
}
</script>
</body>
</html>
【问题讨论】:
-
是的,到处都是相同的属性。但是,您可能希望将初始化
myFunction.flag = 1;放在函数之外,这样它就不会在每次调用函数时都运行......
标签: javascript static