remove(function(item) { condition }) 方法



說明

Knockout.js Observable remove(function(item) { return condition }) 方法刪除滿足條件的專案,並以陣列形式返回它們。

語法

arrayName.remove(function(item) { return condition })

引數

此方法接受一個函式形式的引數,該函式包含條件。陣列中滿足所述條件的專案將被刪除。

示例

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray function based remove method</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p>Example to demonstrate function based remove() method.</p>
      <button data-bind = "click: removeoncondEmp">Remove on condition</button>
      <p>Array of employees: <span data-bind = "text: empArray()" ></span></p>

      <script>
         function EmployeeModel() {
            this.empName = ko.observable("");
            this.chosenItem = ko.observableArray("");
            this.empArray = ko.observableArray(['Scott','James','Jordan','Lee',
               'RoseMary','Kathie']);

            this.removeoncondEmp = function() {
               alert("This function is removing items whos value is 'James'.");
               this.empArray.remove(function (empName) { return empName === 'James' });  
                  //remove where empName is James
            }
         }

         var em = new EmployeeModel();
         ko.applyBindings(em);
      </script>
      
   </body>
</html>

輸出

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

  • 將上面的程式碼儲存在 array-remove-fun.htm 檔案中。

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

  • 單擊條件按鈕上的刪除。

knockoutjs_observables.htm
廣告
© . All rights reserved.