简体   繁体   English

单击5次后是否可以禁用按钮?

[英]Is it possible to diable a button after it has been clicked 5 times?

After a user clicks the button five times, I want the button to become disabled. 用户单击按钮五次后,我希望该按钮被禁用。

Is it possible to just do in html, or would I need to use javascript? 是否有可能只是在html中做,还是我需要使用javascript?

First of all you can give every button a data-clicks attribute. 首先,您可以为每个按钮赋予data-clicks属性。 which contains the number of clicks for this button. 其中包含此按钮的点击次数。

Every time the user click any button check data-clicks attribute value if it equals 5. then disable the button. 每次用户单击任何按钮时,请检查data-clicks属性值是否等于5。然后禁用该按钮。 else just increase the number stored in data-clicks 否则只需增加存储在data-clicks的数量

Example

You can only click 5 times for every button, after that the button will be disabled 每个按钮只能单击5次,之后该按钮将被禁用

 let btns = document.querySelectorAll(".my-btn"), btn = null; for (let i = 0; i < btns.length; i += 1) { btns[i].onclick = function () { this.setAttribute('data-clicks', Number(this.getAttribute('data-clicks')) + 1) if (this.getAttribute('data-clicks') === '5') { this.setAttribute('disabled', 'disabled'); } } } 
 <input type="button" class="my-btn" value="button 1" data-clicks="0"> <input type="button" class="my-btn" value="button 2" data-clicks="0"> <input type="button" class="my-btn" value="button 3" data-clicks="0"> <input type="button" class="my-btn" value="button 4" data-clicks="0"> <input type="button" class="my-btn" value="button 5" data-clicks="0"> 

I removed the array because there is no need for it. 我删除了数组,因为没有必要。 also without it will work dynamically with your html buttons. 也没有它将与您的HTML按钮动态地工作。 you can easily remove or add buttons without any edits for your JavaScript code 您可以轻松删除或添加按钮,而无需对JavaScript代码进行任何编辑

UPDATE 更新

for your jsfiddle you can embed my code in your myno function like this https://jsfiddle.net/bhoLbu8x/5/ 对于您的jsfiddle,您可以将我的代码嵌入到myno函数中,例如https://jsfiddle.net/bhoLbu8x/5/

Hope this gives you some idea: 希望这给您一些想法:

var h = [2, 4, 6, 3, 4, 2, 7];
var button = document.getElementsByTagName('button');
var placementOfValueReaches5 = [];

h.forEach(function(value, index){
    if (value >= 5){
        button[index].setAttribute('disabled', true);
        placementOfValueReaches5.push(index);
    }
});

console.log(placementOfValueReaches5);  // outputs [2, 6]

More information of Array.prototype.forEach here . Array.prototype.forEach更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM