KnockoutJS - 如果不繫結



如果沒有繫結就是 if 繫結的否定。它只是 if 繫結的另一種形式。

語法

ifnot: <binding-condition>

引數

  • 引數是您要檢查的條件。如果該條件評估為真或類真值,那麼將處理給定的 HTML 標記。否則,它將從 DOM 中刪除。

  • 如果引數中的條件包含可觀察值,那麼無論何時可觀察值發生更改,都會重新評估條件。相應地,將根據條件結果新增或刪除相關標記。

示例

讓我們來看一個展示如何使用 ifnot 繫結的示例。

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ifnot binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <p><strong>Product details</strong></p>
      
      <table border = "1">
         <thead>
            <th>Product Name</th><th>Price</th><th>Nature</th>
         </thead>
         
         <tbody data-bind = "foreach: productArray ">
            <tr>
               <td><span data-bind = "text: productName"></span></td>
               <td><span data-bind = "text: price"></span></td>
               <td data-bind = "ifnot: $data.price < 200 ">Expensive</td>
            </tr>
         </tbody>
      </table>

      <script type = "text/javascript">
         function AppViewModel() {
            self = this;
            self.productArray = ko.observableArray([
               {productName: 'Milk', price: 100},
               {productName: 'Oil', price: 10},
               {productName: 'Shampoo', price: 1200}
            ]);
         };
         
         var vm = new AppViewModel();
         ko.applyBindings(vm);
      </script>
      
   </body>
</html>

輸出

讓我們執行以下步驟,瞭解上面的程式碼是如何工作的 −

  • 將上述程式碼儲存到if-not-bind.htm 檔案中。

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

  • 此示例將根據價格填充第三列,該列說明產品性質(昂貴或不昂貴)。請注意,使用 $data 繫結上下文訪問單個屬性。

knockoutjs_declarative_bindings.htm
廣告
© . All rights reserved.