Encoded HTML in optionsText binding of knockout js

2019-08-08 17:48发布

问题:

I am trying to create a dropdown list with html encoded options in knockout js using options binding.

How can i decode the text returned from the function binded to the optionsText binding.

<select data-bind="options: items, optionsText: function(item){ return "decoded text"}"></select>

In general, I need a function that take a encoded html string and returns the decoded text.

i.e. the function takes something like

blah blah balh <sup>TM</sup>

and return

blah blah blah ™

回答1:

This will not be possible. An option tag is not permitted to have other tags as content, only "Normal character data". This does mean you can use entities, e.g. &#8482; or &trade; (which renders as "™"), which should work for your specific example.

For completeness sake, for the Knockout part, if you were to try what you're after, you have two options:

  • utilize the foreach binding and create your own option elements with html bound contents (as opposed to text bound contents)
  • utilize the optionsAfterRender binding to tweak the rendered option elements (thanks to @CaseyWebb for noting this option in the comments)