Knockoutjs : How to add title to options in select

2019-06-23 19:09发布

问题:

I use Knockoutjs options binding to populate my selects as this

<select data-bind="value: val, options: options, optionsText: 'text', optionsValue: 'ID'">
</select>

But for some option, the text is the same. Then I would like to add a title attribute to add information. Can I do that with knockout without modifying knockoutjs itself ?

May be using a function in optionsText, but I can't see How

回答1:

You can do it using the foreach binding, like this:

<select data-bind="foreach: options, value: selectedValue">
    <option data-bind="value: ID, text: text, attr: {title: title}" ></option>
</select>

Here is a working example.