目录

attr: <binding-object>

此绑定允许您使用ViewModel属性动态分配HTML元素attribute 。 例如,您可以根据ViewModel中的值设置图像的src属性,HTML页面的title属性或标记中链接的href

语法 (Syntax)

attr: <binding-object>

参数 (Parameter)

  • JavaScript对象应作为参数传递,其中属性名称引用属性名称,值引用要传递给DOM元素的所需值。

  • 也可以一次分配多个属性。 假设您要分配标题并href一个值,那么绑定将如下所示 -

<a data-bind = "attr: { href: courseUrl, title: courseTitle}">

courseUrlcourseTitle变量将在ViewModel中具有所需的值。

  • 如果ViewModel属性是可观察值,则根据新更新的参数值分配属性。 如果它不是可观察值,则属性仅首次分配一次。

例子 (Example)

让我们看一下下面的示例,该示例演示了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://iowiki.com/");
         };
         var vm = new AppViewModel();
         ko.applyBindings(vm);
      </script>
   </body>
</html>

输出 (Output)

让我们执行以下步骤来查看上述代码的工作原理 -

  • 将以上代码保存在attr-bind.htm文件中。

  • 在浏览器中打开此HTML文件。

  • courseUrl会将值赋给HTML DOM元素中的href属性。

新页面打开
↑回到顶部↑
WIKI教程 @2018