如何在data-bind选择选项中添加标题

时间:2018-05-24 02:00:09

标签: html knockout.js data-binding

我一直在研究如何在选项属性中添加标题,因为我的select标签是数据绑定的,以动态生成选项内容

                            <select class="form-control test" style="height:220px;" multiple="multiple" data-bind="options: $parent.InitiatorFields, optionsText: 'FieldDescription', optionsValue: 'FieldCode', selectedOptions: $root.selectedFromListRule "></select>

我想发生类似这样的事情

<select class="form-control test" style="height:220px;" multiple="multiple" data-bind="options: $parent.InitiatorFields, optionsText: 'FieldDescription', optionsValue: 'FieldCode', selectedOptions: $root.selectedFromListRule ">
<option data-bind="attr {title: 'FieldDescription'}"></option>

这可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用已记录hereoptionsAfterRender

  

如果需要在生成的选项元素上运行一些其他自定义逻辑,则可以使用optionsAfterRender回调。每次将选项元素插入列表时,都会调用回调函数,并使用以下参数:

所以你想要的样本是:

var VM = function(){
  this.options = ko.observableArray(["Option 1", "Option 2", "Option 3"]);
  this.selectedOptions = ko.observableArray(["Option 2"]);
  this.setTitle = function(option, item){
    ko.applyBindingsToNode(option, {attr: {title: "FieldDescription"}});
    // option.title = "FieldDescription"; // Or this line directly
  }
}

ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select multiple="true" data-bind="options: options, selectedOptions: selectedOptions, optionsAfterRender: setTitle">