首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jquery switchery需要限制所选交换机的数量

jquery switchery需要限制所选交换机的数量
EN

Stack Overflow用户
提问于 2016-01-21 04:44:11
回答 2查看 613关注 0票数 0

我有一个页面与多个复选框选择各种选项,用户被允许选择最多6个选项。

使用以下代码,我可以很好地使用标准的html复选框:

代码语言:javascript
复制
$('.ios-switch').on('click', function(e) {
var num_checked = 0;
$('.ios-switch').each(function() { if ($(this).prop('checked')) { num_checked++; } });
if (num_checked > 6) { $(this).prop('checked', false); }
});

此后,我添加了jquery switchery库,将复选框转换为iOS样式的开关。

我使用下面的代码进行设置:

代码语言:javascript
复制
var elems = Array.prototype.slice.call(document.querySelectorAll('.ios-switch'));
elems.forEach(function(html) {
var switchery = new Switchery(html, { size: 'small' });
});

它适用于设置页面上所有复选框的样式,但现在限制选择数量的第一段代码不再起作用。

我已经尝试了switchery站点上的各种代码片段和方法,但我无法恢复开始时的功能,即用户只能选择最多6个选项。

EN

回答 2

Stack Overflow用户

发布于 2016-01-21 05:19:48

看起来您需要使用一个简单的change事件处理程序:

代码语言:javascript
复制
function limitChecksTo(n) {

  // ensures the passed-in number is a Number,
  // even if entered as a String (eg: '6');
  n = parseInt(n, 10);

  // converting the NodeList from document.querySelectorAll()
  // into an Array (ECMAScript 6):
  var checkboxes = Array.from(

      // finding all the <input> elements whose type is 'checkbox'
      // and have a class-name of 'ios-switch':
      document.querySelectorAll('input[type=checkbox].ios-switch')
      );

  // 'this' is passed in automatically
  // from EventTarget.addEventListener()
  // and is the element that has the
  // event-listener attached:
  this.checked = checkboxes

  // filtering the array of checkboxes to retain
  // only those that are checked (using Arrow functions)
    .filter(checkbox => checkbox.checked)
  // if the length is less than n + 1 we
  // we set the checked state of the element firing
  // the event to true, otherwise to false:
    .length < n + 1;
}

// iterating over the 'elems' using Array.prototype.forEach():
elems.forEach(function (html) {
  var switchery = new Switchery(html, { size: 'small' });

  // setting the limitChecksTo() function as the
  // event-handler for the 'change' event:
  html.addEventListener('change', limitChecksTo(6));
});

参考文献:

票数 0
EN

Stack Overflow用户

发布于 2016-01-22 01:09:50

无法使用switchery实现此功能,而且看起来任何解决方案都将非常复杂。

最后,我发现了另一个jquery库iosCheckbox,它的使用和控制要简单得多。

http://www.jqueryscript.net/form/iOS-Style-Checkbox-Plugin-with-jQuery-CSS3-iosCheckbox-js.html

我能够设计样式使iosCheckbox看起来完全像switchery,所以没有明显的前端差异,但后端代码要小得多,而且我的解决方案运行得更快!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34910130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档