尝试使用变量 (var checkTrueMrk
) 作为标记/状态来确定 if 条件。
在按钮上单击,如果“checkTrueMrk
”变量为 true,则 if 条件不会继续,否则 checkTrueMrk 将设置为 true。但是,重复单击时,checkTrueMrk 始终以 false 开头。
可以这样使用变量吗?我知道可以使用对象字面量或构造函数中的对象,在其中我可以创建一个属性,甚至只是在函数外部设置一个全局变量。
编辑** 但是,为什么该变量在设置为 true 后在后续点击中默认为“false”?
我的代码:
<button onclick="myFunction()">click</button>
<script>
function myFunction() {
console.log(checkTrueMrk); //undefinied
console.log(typeof checkTrueMrk); //undefined
if (typeof checkTrueMrk == 'undefined' || !checkTrueMrk) {
var checkTrueMrk = false;
}
console.log(checkTrueMrk); //displays false and type of boolean as expected
if(!checkTrueMrk){
console.log("Im not true");
checkTrueMrk = true;
console.log("I am now set to " + checkTrueMrk
+ "and I am type of"
+ typeof checkTrueMrk);
}
}
最佳答案
您提到您需要变量来充当标志,但不希望它是全局的。如果我理解正确,下面使用自执行匿名函数的方法可能适合您。
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>
<script>
var myFunction = (function() {
alert("came in");
var checkTrueMrk = false;
return function(){
if(!checkTrueMrk){
alert("I will be called once");
checkTrueMrk = true;
}
};
})();
</script>
</body>
</html>
开启
However why does the variable default to 'false' on subsequent clicks after it has been set to true ?
这只是因为在您的实现中,变量的作用域位于函数内。函数调用结束后,其中声明的变量就不存在了。
关于javascript - 将变量分配为函数内的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29755256/