- KnockoutJS 教程
- KnockoutJS - 主頁
- KnockoutJS - 概述
- KnockoutJS - 環境設定
- KnockoutJS - 應用程式
- KnockoutJS - MVVM 框架
- KnockoutJS - 可觀察物件
- 計算的可觀察物件
- KnockoutJS - 宣告式繫結
- KnockoutJS - 依賴項跟蹤
- KnockoutJS - 模板
- KnockoutJS - 元件
- KnockoutJS 資源
- KnockoutJS - 快速指南
- KnockoutJS - 資源
- KnockoutJS - 討論
KnockoutJS - splice() 方法
說明
KnockoutJS 可觀察物件 splice() 方法採用 2 個引數,用於指定 startIndex 和 endIndex。它從 startIndex 到 endIndex 處刪除項並作為陣列返回這些項。
語法
arrayName.splice(start-index,end-index)
引數
接受 2 個引數,start-index 是開始索引,end-index 是結束索引。
示例
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray splice 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 splice() method.</p>
<button data-bind = "click: spliceEmp">Splice Emp</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.spliceEmp = function() {
alert("Splice is removing items from index 1 to 3(If exists).");
this.empArray.splice(1,3); // remove 2nd,3rd and 4th item, as array index
//starts with 0.
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
輸出
讓我們執行以下步驟,看看上述程式碼是如何工作的:
將上述程式碼儲存在 array-splice.htm 檔案中。
在瀏覽器中開啟此 HTML 檔案。
單擊 Splice 僱員按鈕,觀察到從索引 1 到 3 的項被刪除了。
knockoutjs_observables.htm
廣告