第三次点击后隐藏按钮



我制作了按钮,当你点击它们时,它会从绿色变为红色再变为黄色。现在我想补充一点,当你在按钮颜色变为黄色后点击按钮时,按钮将不再显示。

我试着用

if (color[change > 2]){
button.style.display = "none";
}

但是这似乎不起作用。。有没有一种方法可以在不改变太多代码的情况下将其添加到函数中?

var color=["绿色"、"红色"、"黄色"];

function page() {
document.body.style.backgroundColor = "purple";
//style page
createButtons(10);
}
page();
function onbuttonclicked(a) {
var Amount = document.getElementById("button" + a);
var click = Amount.getAttribute('Color');
var change = color.indexOf(click);
Amount.setAttribute('style', 'background-color:' + color[change + 1]);
Amount.setAttribute('Color', color[change + 1]);
if (color[change > 2]){
button.style.display = "none";
}
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function createButtons(amount) {
for (var a = 1; a <(amount + 1); a++) {
var button = document.createElement("button");
button.id = "button" + a;
button.innerHTML = "button " + a;
button.setAttribute('Color', color[0]);
button.setAttribute('style', 'background-color:' + color[0]);
container.appendChild(button);
}
set_onclick(amount);
}

let count = -1;
let color = ["green", "red", "yellow"];
document.querySelector('button').addEventListener('click', function() {
if (color[++count]) {
this.style.backgroundColor = color[count];
} else {
this.style.display = 'none';
}
});
<button type="button">Click me</button>

您可以声明一个变量,该变量在每次单击按钮时都会增加,然后当变量达到某个值时,您可以删除按钮

var count=0;
function onButtonClick(){
/your code here
if(count>2){
/delete button
}
count++;
}

最新更新