KnockoutJS - Attr 绑定
此绑定允许您使用 ViewModel 属性动态分配 HTML 元素 attribute。例如,您可以根据 ViewModel 中的值在标签中设置图像的 src 属性、HTML 页面的 title 属性或链接的 href。
语法
attr: <binding-object>
参数
JavaScript 对象应作为参数传递,其中属性名称指的是属性名称,值指的是要传递给 DOM 元素的所需值。
也可以一次分配多个属性。假设您要为 title 和 href 分配值,则绑定将如下所示 −
<a data-bind = "attr: { href: courseUrl, title: courseTitle}">
courseUrl 和 courseTitle 变量将在 ViewModel 中具有所需的值。
如果 ViewModel 属性是可观察值,则根据新更新的参数值分配属性。如果它不是可观察值,则属性仅在第一次分配一次。
示例
让我们看一下以下示例,该示例演示了如何使用 Attr 绑定。
<!DOCTYPE html> <head> <title>KnockoutJS attribute binding</title> <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" type = "text/javascript"></script> </head> <body> <a data-bind = "attr: { href: courseUrl}"> Click here for free online tutorials and courses. </a> <script type = "text/javascript"> function AppViewModel() { this.courseUrl = ("http://tutorialspoint.com/"); }; var vm = new AppViewModel(); ko.applyBindings(vm); </script> </body> </html>
输出
让我们执行以下步骤来查看上述代码的工作原理 −
将上述代码保存在 attr-bind.htm 文件中。
在浏览器中打开此 HTML 文件。
courseUrl 将为 HTML DOM 元素中的 href 属性分配值。
knockoutjs_declarative_bindings.html