首页 > 网站 > WEB开发 > 正文

table通过每行的checkbox(多个)判断选中的行并把数据储存成json格式

2024-04-27 15:18:38
字体:
来源:转载
供稿:网友

一、通过查找数组里是否存在选中的数据来操作:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>checkbox</title>    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script></head><body><input type="checkbox" onclick="ck('111')">111<input type="checkbox" onclick="ck('222')">222<input type="checkbox" onclick="ck('333')">333<input type="checkbox" onclick="ck('444')">444</body><script>    var selectedList =[];    function ck(v) {        var hasS = false;        for (var i = 0; i < selectedList.length; i++) {            if (selectedList[i] == v) {                selectedList.splice(i, 1);                hasS = true;            }        }        if(!hasS){            selectedList.push(v);        }    }</script></html>

以上方法针对每条数据都是独一无二的,修改了一下就好了

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>checkbox</title>    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script></head><body><input type="checkbox" onclick="ck('111',this)"><input type="checkbox" onclick="ck('111',this)"><input type="checkbox" onclick="ck('333',this)"><input type="checkbox" onclick="ck('444',this)"></body><script>    var selectedList =[];    function ck(v,n) {        if(n.checked){            selectedList.push(v);                    }else {            for (var i = 0; i < selectedList.length; i++) {                if (selectedList[i] == v) {                    selectedList.splice(i, 1);                                    }            }        }    }</script></html>

二、因为我使用了angular那就写法又可以这样:

<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title>checkbox</title>    <script src="../js/angular.js"></script>    <script src="../js/jquery.min.js"></script></head><body ng-app="myNg" ng-controller="ngCtrl"><input type="checkbox" ng-model="selectState" ng-click="ck(item.text,selectState)" ng-repeat="item in arr"></body><script>    angular.module('myNg',[]).controller('ngCtrl',function($scope,$log) {        $scope.arr= [{text:'111'},{text:'222'},{text:'333'},{text:'444'}];        $scope.selectedList = [];        $scope.selectState =false;        $scope.ck =function(v,stu) {            if(stu){                $scope.selectedList.push(v);            }else {                for (var i = 0; i < $scope.selectedList.length; i++) {                    if ($scope.selectedList[i] == v) {                        $scope.selectedList.splice(i, 1);                    }                }                //或者JQ的                //$scope.selectedList.splice($.inArray(v, $scope.selectedList), 1);            }        }    })</script></html>


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表