javascript中使用splice删除数组的问题

<!DOCTYPE html >
< html lang= "en" >

< head >
< meta charset= "UTF-8" >
< meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
< meta http-equiv= "X-UA-Compatible" content= "ie=edge" >
< title >Document </ title >
< link rel= "stylesheet" href= "./bootstrap.css" >
< script src= "../angular-1.6.6/angular.js" > < / script >
< link rel= "stylesheet" href= "./toDoList.css" >
< script >
( function( angular) {
var app = angular. module( 'myApp', []);
app. controller( 'MyController', [ '$scope', function( $scope) {
$scope. dataList = [];
$scope. finished = null;
$scope. add = function() {
$scope. dataList. push({
a: $scope. data,
b: false
});
console. log( $scope. dataList);
};
$scope. delet = function( $event) {
$scope. dataList. splice( this. $index, 1);
}
$scope. empty = function() {
$scope. dataList = [];
}
$scope. checkedbox = function( $event) {
$scope. dataList[ this. $index]. b = ! $scope. dataList[ this. $index]. b;
// if (event.target.checked) {
// console.log(this.$index);
// // $scope.selected = finished;
// }
}
$scope. del_selected = function() {
//这里用splice删除所选中的元素,但是如果从前往后删除导致数组长度发生变化,每次删除一个之后循环就终止了。
//但是如果从后往前删的话这个问题就不存在
for ( var i = $scope. dataList. length - 1; i >= 0; i--) {
if ( $scope. dataList[ i]. b) {
$scope. dataList. splice( i, 1);
}
}
}
}]);
})( angular);
< / script >
</ head >

< body ng-app= "myApp" ng-controller= "MyController" >
< h1 >To DO List </ h1 >
< div class= "container self-container" >
< input ng-model= "data" type= "text" class= "form-control self-inp" id= "exampleInputEmail2" placeholder= "输入信息" >
< button ng-click= "add()" class= "btn btn-primary self-add" >添加 </ button >
< div class= "self-list" >
< div class= "checkbox" >
< div ng-repeat= "item in dataList track by $index" class= "self-item-list" >
< input type= "checkbox" value= "" ng-checked= "item.b" ng-click= "checkedbox()" ng-model= "selected" >
< span ng-class= "{true: 'finished'}[item.b]" >{{item.a}} </ span >
< button class= "btn btn-primary self-xx" ng-click= "delet()" >&times; </ button >
</ div >
</ div >
</ div >
< div class= "btn-box" >
< button class= "btn btn-primary self-btn-del" ng-click= "del_selected()" >删除所选项 </ button >
< button class= "btn btn-primary self-btn-empty" ng-click= "empty()" >清空 </ button >
</ div >

</ div >
</ body >

</ html >

猜你喜欢

转载自blog.csdn.net/qq_28949081/article/details/78441408
今日推荐