- KnockoutJS 教程
- KnockoutJS - 主页
- KnockoutJS - 概览
- KnockoutJS - 环境设置
- KnockoutJS - 应用程序
- KnockoutJS - MVVM 框架
- KnockoutJS - 可观察对象
- 计算型可观测对象
- KnockoutJS - 声明性绑定
- KnockoutJS - 依赖项跟踪
- KnockoutJS - 模板
- KnockoutJS - 组件
- KnockoutJS 资源
- KnockoutJS - 快速指南
- KnockoutJS - 资源
- KnockoutJS - 讨论
KnockoutJS - unshift() 方法
说明
KnockoutJS 可观察对象unshift('value')方法在数组开头插入一个新项目。
语法
arrayName.unshift('value')
参数
接受一个要插入的值的参数。
示例
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray unshift 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 unshift() method.</p>
<p>Enter name: <input data-bind='value: empName' /></p>
<button data-bind="click: unshiftEmp">Add Emp in Beginning</button><br><br>
<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.unshiftEmp = function() {
if (this.empName() != "") {
this.empArray.unshift(this.empName()); // insert at the beginning
this.empName("");
}
}.bind(this);
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
输出
让我们执行以下步骤,看上述代码如何工作 −
将上述代码保存在array-unshift.htm文件中。
在浏览器中打开此 HTML 文件。
输入名称为 Tom,然后单击在开头添加员工按钮。
knockoutjs_observables.htm
广告