【问题标题】:buttonset() not working with dynamic inputsbuttonset() 不适用于动态输入
【发布时间】:2015-05-29 19:16:07
【问题描述】:

我正在尝试将 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>

【问题讨论】:

  • 如果可能的话,能否显示html代码?
  • 对不起,我认为这无关紧要
  • 它在您进行 DOM 操作时很有帮助,因此可以快速查看结构而不是推断结构。以防万一还有其他东西可能会弄乱代码。 :D

标签: javascript jquery jquery-ui jquery-ui-button


【解决方案1】:

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

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

文档说

为使关联正常工作,请为输入提供一个 id 属性,并在标签的 for 属性中引用该属性。不要将输入嵌套在标签内,因为这会导致可访问性问题。


$(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>

【讨论】:

  • 谢谢!如果我将标签 + 输入放入 div 会不会有问题?所以我不必同时隐藏/显示(),这就是我嵌套的原因。
  • 嗯,现在我意识到复选框的顺序...在我的页面中,我看到的是从 30 到 1 而不是代码 sn-p 顺序,你知道为什么吗???
  • 因为如果你使用 append,它会添加到末尾,你可能想使用 $.prepend
  • @ChazyChaz:在您的代码中,您使用的是导致问题的 prepend。你确定你还在用 append 吗?
  • @DhirajBodicherla Jquery 包含一个 prepend 方法,这不是问题,我相信这是导致问题的 for 属性(请参阅api.jquery.com/prepend
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多