KnockoutJS - remove() 方法

描述

KnockoutJS Observable remove('value') 方法删除与"value"匹配的项目并返回数组。

语法

arrayName.remove('value')

参数

接受一个参数作为要删除的值。

示例

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray 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 remove() method.</p>
      <button data-bind = "click: removeEmp">Remove selected Emp</button>
      <p>Array of employees:</p>
      <select multiple = "true" size = "8" data-bind = "options: empArray , 
         selectedOptions: chosenItem"> </select>

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

            this.removeEmp = function(chosenItem) {
               
               if (this.chosenItem().length == 0)  {
                  alert("Please select item/s to be removed.");
               }
               
               while(this.chosenItem().length > 0) {
                  this.empArray.remove(this.chosenItem()[0]);
               }
            }
         }

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

输出

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

  • 将上述代码保存在 array-remove.htm 文件中。

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

  • 选择要从列表中删除的项目,然后单击"删除所选 Emp"按钮。

knockoutjs_observables.html