我正在尝试创建一些东西,使按钮只能工作一次。为此,我创建了一个 if 循环。在该 if 循环中,我将其放入一个名为 myFunction 的函数中,然后将变量 Button 设置为 0(if 循环仅在 Button =2 时运行。它首先不会运行。我做错了什么?
我已经尝试重新创建变量(在循环外说一次 var 按钮,然后在循环内再说一次)。
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var button = 2;
var x = 0
function ins() {
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
x = getRndInteger(0, window.innerWidth)
alert(x);
}
function button() {
if (button === 2) {
alert("k")
myFunction();
button = 0;
} else {}
}
function myFunction() {
var para = document.createElement("SPAN");
para.style.position = "absolute";
x = getRndInteger(0, (window.innerWidth - 60))
para.style.left = x + "px"
var p = getRndInteger(0, (window.innerHeight - 60))
para.style.top = p + "px"
para.style.display = "inline-block;"
para.style.height = "50px"
para.style.width = "50px"
para.style.backgroundColor = "red"
para.style.borderRadius = "50px"
para.style.border = "1px solid black"
para.style.animation = "1s a linear"
para.id = "a"
para.onclick = myFunction
document.getElementById("myDIV").appendChild(para);
}
@keyframes a {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
button {
background-color: #010417;
border-radius: 10px;
border: 4px solid white;
color: white;
padding: 10px 26px;
font-size: 20px;
}
<div id="myDIV"></div>
<center>
<button id="button" onClick="button();">Start</button>
</center>
编辑:忽略删除功能,没有任何意义
最佳答案
此代码的问题在于您的事件处理函数和标志(在 2 和 0 之间更改值)都被命名为“button”。 Javascript是一种相对包容的语言,因此这种双重声明可能不会立即抛出错误,但显然会导致意外的行为。
查看您的代码:
var button = 2;
function button() {
if (button === 2) {
alert("k")
myFunction();
button = 0;
} else {}
}
在这种情况下(取决于 JS 引擎),按钮要么指功能,要么指数字。如果是数字,则单击按钮时将引发类型错误。因为代码会尝试像函数一样调用该数字。
如果它是一个函数,那么 button === 2
比较将始终为 false,并且(空)else block 将被执行。无论哪种方式,你都不会得到预期的行为。您只需将变量名称更改为其他名称即可,它应该可以工作。
请注意,正如有人在评论中指出的那样,您应该更愿意向按钮添加 disabled
属性而不是此逻辑。除非目的不是阻止多次点击按钮。
关于javascript - 变量值不保存在 if 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55907501/