您将如何验证某人只会检查不超过2个选项?这是一个非常奇怪的问题,谷歌搜索,找不到文章。我更喜欢JS方法。
<select multiple>
<option value="cheese">Cheese</option>
<option value="pepperoni">Pepperoni</option>
<option value="sausage">Sausage</option>
<option value="mushrooms">Mushrooms</option>
</select>
答案 0 :(得分:1)
您将查看选择的click
事件中的selectedOptions.length
,然后在该计数大于2时不允许进一步选择。
$(function() {
// Get references to the different select elements and convert
// them into Arrays:
var pizzaSelect =
Array.prototype.slice.call(
document.querySelectorAll("#pizzaOptions > option"));
var sodaSelect =
Array.prototype.slice.call(
document.querySelectorAll("#soda > option"));
// Loop over each list's options, executing the supplied
// callback function for each one.
pizzaSelect.forEach(checkSelectionCount);
sodaSelect.forEach(checkSelectionCount);
function checkSelectionCount(opt, idx, ary){
// Add a click event listener to each option:
opt.addEventListener("click", function(event){
// Is a 3rd option clicked and being selected?
if(this.parentNode.selectedOptions.length === 3 && this.selected) {
this.selected = false; // De-select it.
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple id="pizzaOptions">
<option value="cheese">Cheese</option>
<option value="pepperoni">Pepperoni</option>
<option value="sausage">Sausage</option>
<option value="mushrooms">Mushrooms</option>
</select>
<br><br>
<select multiple id="soda">
<option value="coke">Coke</option>
<option value="sprite">Sprite</option>
<option value="dr_pepper">Dr. Pepper</option>
</select>