仅允许用户选择最多三个块

时间:2018-03-26 12:51:33

标签: javascript html css

我有一段代码可以向多个按钮添加一个事件监听器,当用户单击一个按钮时,一个类被应用于按钮容器。如何限制此项,以便用户最多只能选择三个按钮。下面的代码是有用的,当你达到三个时,你无法取消选择。任何人都可以帮我实现

var blocks = document.querySelectorAll(".block");
var btn = document.querySelectorAll("button");
var total = 0;

for (let i = 0; i < btn.length; i++) {
  btn[i].addEventListener("click", function() {
    if (total < 3 && blocks[i].classList.contains("active")) {
      blocks[i].classList.remove("active");
      total--;
    } else if (total < 3 && !blocks[i].classList.contains("active")) {
      blocks[i].classList.add("active");
      total++;
    }
  });
}
.container{
  display:flex;
}
.block{
  padding: 50px;
  border:1px solid;
  max-width:
}
.block.active{
  background:grey;
}
<div class="container">
  <div class="block">
    <button>click</button>
  </div>
  <div class="block">
    <button>click</button>
  </div>
  <div class="block">
    <button>click</button>
  </div>
  <div class="block">
    <button>click</button>
  </div>
  
</div>

此。

1 个答案:

答案 0 :(得分:4)

您只需要从第一个total < 3 &&中删除此条件if即可。如果已选择元素,则所选项目的数量无关紧要。你只想取消选择它。

&#13;
&#13;
var blocks = document.querySelectorAll(".block");
var btn = document.querySelectorAll("button");
var total = 0;

for (let i = 0; i < btn.length; i++) {
  btn[i].addEventListener("click", function() {
    if (blocks[i].classList.contains("active")) {
      blocks[i].classList.remove("active");
      total--;
    } else if (total < 3 && !blocks[i].classList.contains("active")) {
      blocks[i].classList.add("active");
      total++;
    }
  });
}
&#13;
.container{
  display:flex;
}
.block{
  padding: 50px;
  border:1px solid;
  max-width:
}
.block.active{
  background:grey;
}
&#13;
<div class="container">
  <div class="block">
    <button>click</button>
  </div>
  <div class="block">
    <button>click</button>
  </div>
  <div class="block">
    <button>click</button>
  </div>
  <div class="block">
    <button>click</button>
  </div>
  
</div>
&#13;
&#13;
&#13;