KnockoutJS - HTML 繫結



HTML 繫結使關聯的 DOM 元素顯示引數指定的 HTML。如果您想動態生成 HTML 標記,這很有用。

語法

html: <binding-value>

引數

  • KnockoutJS 將 DOM 元素的內容設定為提供的引數值。此功能在 JQuery 中也可用。如果 JQuery 不可用於實現此功能,則可以使用 KO。

  • 如果引數是可觀察物件,則會在底層可觀察物件更改時更新元素值。如果不使用可觀察物件,則元素僅處理一次。

示例

我們來看看以下顯示如何使用 html 繫結的示例。

<!DOCTYPE html>
   <head>
      <title>KnockoutJS Html binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <p><span data-bind="html: welcomeMessgae "></span></p>
      
      <script>
         function AppViewModel() {
            this.welcomeMessgae = ko.observable();
            this.welcomeMessgae ("<strong>Welcome to TutorialsPoint !!! For free online tutorials and courses click <a href = 'https://tutorialspoint.tw/'>here</a>.</strong>");
         }
         
         ko.applyBindings(new AppViewModel());
      </script>
      
   </body>
</html>

結果

讓我們執行以下步驟,瞭解上述程式碼如何執行 −

  • 將上述程式碼儲存在html-bind.htm檔案中。

  • 在瀏覽器中開啟此 HTML 檔案。

knockoutjs_declarative_bindings.htm
廣告
© . All rights reserved.