入门

监控属性

使用内置绑定

控制文本和外观

绑定逻辑控制

处理表单属性

解析模板

高级应用

插件

更多信息

"html" 绑定

目的

html 绑定到DOM元素上,使得该元素显示的HTML值为你绑定的参数。

The html binding causes the associated DOM element to display the HTML specified by your parameter.

如果在你的view model里声明HTML标记并且render的话,那非常有用。

Typically this is useful when values in your view model are actually strings of HTML markup that you want to render.

例子

  1. <div data-bind="html: details"></div>
  2. <script type="text/javascript">
  3. var viewModel = {
  4. details: ko.observable() // Initially blank
  5. };
  6. viewModel.details("<em>For further details, view the report <a href='report.html'>here</a>.</em>"); // HTML content appears
  7. </script>

参数

  • 主参数

KO设置该参数值到元素的 innerHTML 属性上,元素之前的内容将被覆盖。

KO sets the element’s innerHTML property to your parameter value. Any previous content will be overwritten.

如果参数是监控属性observable的,那元素的内容将根据参数值的变化而更新,如果不是,那元素的内容将只设置一次并且以后不在更新。

If this parameter is an observable value, the binding will update the element’s content whenever the value changes. If the parameter isn’t observable, it will only set the element’s content once and will not update it again later.

如果你传的是不是数字或者字符串(例如一个对象或者数组),那显示的 innerHTML 将是 yourParameter.toString() 的等价内容。

If you supply something other than a number or a string (e.g., you pass an object or an array), the innerHTML will be equivalent to yourParameter.toString()

  • 其他参数

注:关于HTML encoding

因为该绑定设置元素的 innerHTML,你应该注意不要使用不安全的HTML代码,因为有可能引起脚本注入攻击。如果你不确信是否安全(比如显示用户输入的内容),那你应该使用 text 绑定绑定,因为这个绑定只是设置元素的text 值 innerTexttextContent

Since this binding sets your element’s content using innerHTML, you should be careful not to use it with untrusted model values, because that might open the possibility of a script injection attack. If you cannot guarantee that the content is safe to display (for example, if it is based on a different user’s input that was stored in your database), then you can use the text binding, which will set the element’s text value using innerText or textContent instead.

依赖性

除KO核心类库外,无依赖。

None, other than the core Knockout library.

(c) knockoutjs.com