【问题标题】:How to use a template in a select?如何在选择中使用模板?
【发布时间】:2016-02-04 00:46:43
【问题描述】:

我可以通过这样做在 Knockout.js 中创建一个伪选择列表:

<div style="width:325px;height:500px;overflow:auto;" data-bind="template: { name: 'group-tmpl', foreach: explorer().categoryData }"></div>

但您不会像使用 &lt;select&gt; 那样获得样式和选定值。

我尝试执行此操作,但收到一条错误消息,提示您无法在此数据绑定中使用模板。

<select data-bind="options: explorer().categories, value: explorer().selectedCategory, optionsText:'name', template: 'group-tmpl'" size="15" />          

我还尝试在&lt;option&gt; 中指定一个模板,但没有正确呈现(刚刚看到[object Object] 的列表)。

我想要的东西之一是&lt;option&gt; 中的图像。所以我想我可以尝试在加载后使用 css & 使用 jQuery 来设置 attr,但这违背了使用 Knockout 的目的。

我希望我错过了一些明显和/或容易的事情。

【问题讨论】:

  • You can't 在原生 &lt;option&gt; 元素中有图像或其他 HTML。您将需要使用您的第一个代码示例来模拟选择行为,并最终将其封装在自定义绑定中。

标签: javascript jquery html css knockout.js


【解决方案1】:

正如评论者指出的那样,一般来说,options 和 selects 内不能有太多花哨的东西。您需要使用像 Select2ChosenSelectize 这样的库,通常由普通的 select 支持。

不过,要回答您的具体问题,如果您想在 select 中使用模板化的 foreach,您完全可以这样做:

ko.applyBindings({
  items: [
    { txt: "option A" },
    { txt: "option B" },
    { txt: "option C" }
  ]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script type="text/html" id="itemTmpl">
<option>~~~<!-- ko text: txt --><!-- /ko -->~~~</option>
</script>
<select data-bind="template: { name: 'itemTmpl', foreach: items }"></select>

同样,您不能在script 模板内任何花哨的事情,因为您一开始就不能在select 内做任何花哨的事情。但是 可以在选择上使用模板 + foreach。一个有用的典型用例是当您需要(自定义)optgroups 时。另一个用途可能是您希望在 options 上包含特殊属性(也许是 aria- 属性?)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    相关资源
    最近更新 更多