入门

监控属性

使用内置绑定

控制文本和外观

绑定逻辑控制

处理表单属性

解析模板

高级应用

插件

更多信息

attr 绑定

目的

attr绑定提供了一种方式可以设置DOM元素的任何属性值。你可以设置 imgsrc 属性,链接的 href 属性。使用绑定,当模型属性改变的时候,它会自动更新。

The attr binding provides a generic way to set the value of any attribute for the associated DOM element. This is useful, for example, when you need to set the title attribute of an element, the src of an img tag, or the href of a link based on values in your view model, with the attribute value being updated automatically whenever the corresponding model property changes.

例子

  1. <a data-bind="attr: { href: url, title: details }">
  2. Report
  3. </a>
  4. <script type="text/javascript">
  5. var viewModel = {
  6. url: ko.observable("year-end.html"),
  7. details: ko.observable("Report including final year-end statistics")
  8. };
  9. </script>

呈现结果是该链接的 href 属性被设置为 year-end.htmltitle 属性被设置为 Report including final year-end statistics.

This will set the element’s href attribute to year-end.html and the element’s title attribute to Report including final year-end statistics.

参数

  • 主参数

    该参数是一个JavaScript对象,属性是你的attribute名称,值是该attribute需要应用的值。

You should pass a JavaScript object in which the property names correspond to attribute names, and the values correspond to the attribute values you wish to apply.

如果参数是监控属性observable的,那随着值的变化将会自动添加或者删除该元素上的attribute值。如果不是,那attribute值将会只应用一次并且以后不在更新。

If your parameter references an observable value, the binding will update the attribute whenever the observable value changes. If the parameter doesn’t reference an observable value, it will only set the attribute once and will not update it later.

  • 其他参数

注:应用的属性名字不是合法的JavaScript变量命名

如果你要用的属性名称是 data-something的话,你不能这样写:

If you want to apply the attribute data-something, you can’t write this:

  1. <div data-bind="attr: { data-something: someValue }">...</div>

…因为 data-something 不是一个合法的命名。解决方案是:在data-something两边加引号作为一个字符串使用。这是一个合法的JavaScript 对象 文字(从JSON技术规格说明来说,你任何时候都应该这样使用,虽然不是必须的)。例如,

… because data-something isn’t a legal identifier name at that point. The solution is simple: just wrap the identifier name in quotes so that it becomes a string literal. This is legal in a JavaScript object literal (technically, according to the JSON spec, you should always do this anyway, though in practice you don’t have to). For example,

  1. <div data-bind="attr: { 'data-something': someValue }">...</div>

依赖性

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

(c) knockoutjs.com