buttonset()不适用于动态输入

buttonset() not working with dynamic inputs

我正在尝试使用 jquery buttonset() 进行动态输入,但它不起作用:

$(document).ready(function () {
    var N = 30;
    for (var i = 1; i <= N; i++) {
        $('<label/>', {
            id: "label-" + i,
        }).append($('<input/>', {
            type: "checkbox",
            id: "checkbox-" + i
        })).append(i).prependTo("#showChck");
    }

    $("#showChck").buttonset('refresh');
});

只显示标签,不显示输入。

编辑:添加 html 代码:

<div data-role="fieldcontain" id="channels" style="display:none;">
    <fieldset id="showChck" data-role="controlgroup" data-type="horizontal">

    </fieldset>
</div>

标签需要 for 属性才能使按钮集正常工作,而且标签和复选框不应嵌套。

在演示中,我更改了输入和标签的呈现方式 as per the documentation here

文档说

For the association to work properly, give the input an id attribute, and refer to that in the label's for attribute. Don't nest the input inside the label, as that causes accessibility problems.


$(document).ready(function() {
  var N = 30;
  for (var i = 1; i <= N; i++) {
    var $input = $('<input/>', {
      type: "checkbox",
      id: "checkbox-" + i
    });
    var $label = $('<label/>', {
      id: "label-" + i,
      for: "checkbox-" + i
    }).append(i);
    $("#showChck").append($input).append($label);
  }
  $("#showChck").buttonset();
});

$(document).ready(function() {
  var N = 30;
  for (var i = 1; i <= N; i++) {
    var $input = $('<input/>', {
      type: "checkbox",
      id: "checkbox-" + i
    });
    var $label = $('<label/>', {
      id: "label-" + i,
      for: "checkbox-" + i
    }).append(i);
    $("#showChck").append($input).append($label);
  }
  $("#showChck").buttonset();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div data-role="fieldcontain" id="channels" style="display:block;">
  <fieldset id="showChck" data-role="controlgroup" data-type="horizontal">

  </fieldset>
</div>