KnockoutJS - push() 方法
描述
KnockoutJS Observable push('value') 方法在数组末尾插入一个新项。
语法
arrayName.push('value')
参数
仅接受一个参数,即要插入的值。
示例
<!DOCTYPE html> <head> <title>KnockoutJS Observable Array push() 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 push() method.</p> <p>Enter name: <input data-bind = 'value: empName' /></p> <p><button data-bind = "click: addEmp">Add Emp </button></p> <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']); //Initial Values this.addEmp = function() { if (this.empName() != "") { this.empArray.push(this.empName()); //insert accepted value in array this.empName(""); } }.bind(this); } var emp = new EmployeeModel(); ko.applyBindings(emp); </script> </body> </html>
输出
让我们执行以下步骤来查看上述代码的工作原理 −
将上述代码保存在 array-push.htm 文件中。
在浏览器中打开此 HTML 文件。
输入"Tom"并单击"添加 Emp"按钮。