KnockoutJS - uniqueName 繫結



該繫結用於為 DOM 元素生成一個唯一名稱。如果 DOM 元素沒有 name 屬性,此繫結會為其指定一個並將其設定為某個唯一字串值。

你不必經常使用這個。它僅在一些罕見的情況下才有用,例如:-

  • jQuery 驗證目前只會驗證具有名稱的元素。為了將其與 Knockout UI 配合使用,有時需要應用 uniqueName 繫結以避免混淆 jQuery 驗證。

  • 如果 IE 6 中的單選按鈕沒有 name 屬性,那麼無法選中它們。KO 會在那些元素上內部使用 uniqueName 以確保能夠選中它們。

語法

uniqueName: <binding-value>

引數

這裡引數將為 Boolean 值 true 或 false 或是一個產生布爾值的結果表示式。對於為此引數設定為 truetrue 類值那個元素,KO 將生成一個唯一名稱。

示例

讓我們看一個展示 uniqueName 繫結的用法示例。

<!DOCTYPE html>
   <head>
      <title>KnockoutJS UniqueName Binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p>Enter your pet's name: 
         <input data-bind = "value: someValue, uniqueName: true" />
      </p>
   
      <p>
         <button data-bind = "click: showMessage">Click here to read message </button>
      </p>

      <script type = "text/javascript">
         function ViewModel() {
            this.someValue = ko.observable();
         
            this.showMessage = function() {
               alert(" Nice Name"+ "\nSee rendered markup to view unique name generated!!!");
            }
         };

         var vm = new ViewModel();
         ko.applyBindings(vm);
      </script>
      
   </body>
</html>

輸出

讓我們執行以下步驟,看看上面的程式碼是如何工作的:-

  • uniquename-bind.htm 檔案中儲存上面的程式碼。

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

  • 按 F12 並觀察呈現的標記。唯一的名稱由 KO 生成。

knockoutjs_declarative_bindings.htm
廣告
© . All rights reserved.