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

时间:2017-06-18 14:47:35

标签: javascript html html5

用户单击该按钮五次后,我希望该按钮被禁用。

是否可以在html中执行,或者我是否需要使用javascript?

2 个答案:

答案 0 :(得分:1)

首先,您可以为每个按钮指定data-clicks属性。其中包含此按钮的点击次数。

每次用户单击任何按钮时,如果它等于5,请检查data-clicks属性值,然后禁用该按钮。否则只需增加data-clicks

中存储的数字

示例

每个按钮只能点击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">

我删除了数组,因为没有必要。也没有它将动态使用您的HTML按钮。您无需对JavaScript代码进行任何编辑即可轻松删除或添加按钮

<强>更新

对于你的jsfiddle,你可以将我的代码嵌入myno函数中,如https://jsfiddle.net/bhoLbu8x/5/

答案 1 :(得分:1)

希望这会给你一些想法:

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]

Array.prototype.forEach here的更多信息。