CMDB项目CURD组件进入编辑模式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css" />
    <style>

    </style>
</head>
<body>
{#    <select id="i1">#}
{#        <option>上阿海</option>#}
{#        <option>北京</option>#}
{#        <option>广州</option>#}
{#    </select>#}

    <div style="width: 800px;margin: 0 auto;">
        <h1>资产列表</h1>
        <div class="btn-group" role="group" aria-label="...">
          <button id="idCheckAll" type="button" class="btn btn-default">全选</button>
          <button id="idReverseAll" type="button" class="btn btn-default">反选</button>
          <button id="idCancelAll" type="button" class="btn btn-default">取消</button>
          <button id="idEditMode" type="button" class="btn btn-default">进入编辑模式</button>
          <button type="button" class="btn btn-default">批量删除</button>
          <button id="idSave" type="button" class="btn btn-default">保存</button>
          <a id="idAdd" href="/web/asset-add.html" class="btn btn-default">添加</a>
        </div>
        <table class="table table-bordered">
            <thead id="table_th"></thead>
            <tbody id="table_tb"></tbody>
        </table>
        <ul id="idPagination" class="pagination">

        </ul>
    </div>

    <script src="/static/js/jquery-3.1.1.js"></script>
    <script src="/static/js/nbList.js"></script>

    <script>
        $(function () {
            $.NB("/web/asset-json.html");
        });

    </script>

</body>
</html>

asset.html

(function () {
        var requestUrl = null;
        function bindChangePager() {
            $(‘#idPagination‘).on(‘click‘,‘a‘,function () {
                var num = $(this).text();
                init(num);

            })
        }

        function bindSave() {
            $(‘#idSave‘).click(function () {
                var postList = [];
                //找到已经编辑过的tr,tr has-edit=‘true‘
                $(‘#table_tb‘).find(‘tr[has-edit="true"]‘).each(function () {
                    // $(this) => tr
                    var temp = {};
                    var id = $(this).attr(‘row-id‘);
                    temp[‘id‘] = id;
                    $(this).children(‘[edit-enable="true"]‘).each(function () {
                        // $(this) = > td
                        var name = $(this).attr(‘name‘);
                        var origin = $(this).attr(‘origin‘);
                        var newVal = $(this).attr(‘new-val‘);
                        if (origin != newVal){
                            temp[name] = newVal;
                        }
                    });
                    postList.push(temp);
                })

                $.ajax({
                    url:requestUrl,
                    type: ‘PUT‘,
                    data: {‘post_list‘: JSON.stringify(postList)},
                    dataType: ‘JSON‘,
                    success:function (arg) {
                        if(arg.status){
                            init(1);
                        }else{
                            alert(arg.error);
                        }
                    }
                })
            })
        }

        function bindReverseAll() {
            $(‘#idReverseAll‘).click(function () {
                $(‘#table_tb‘).find(‘:checkbox‘).each(function () {
                    // $(this) => checkbox
                    if($(‘#idEditMode‘).hasClass(‘btn-warning‘)) {
                        if($(this).prop(‘checked‘)){
                            $(this).prop(‘checked‘,false);
                            trOutEditMode($(this).parent().parent());
                        }else{
                            $(this).prop(‘checked‘,true);
                            trIntoEditMode($(this).parent().parent());
                        }
                    }else{
                        if($(this).prop(‘checked‘)){
                            $(this).prop(‘checked‘,false);
                        }else{
                            $(this).prop(‘checked‘,true);
                        }
                    }
                })
            })
        }

        function bindCancelAll() {
            $(‘#idCancelAll‘).click(function () {
                $(‘#table_tb‘).find(‘:checked‘).each(function () {
                    // $(this) => checkbox
                    if($(‘#idEditMode‘).hasClass(‘btn-warning‘)){
                        $(this).prop(‘checked‘,false);
                        // 退出编辑模式
                        trOutEditMode($(this).parent().parent());
                    }else{
                        $(this).prop(‘checked‘,false);
                    }
                });
            })
        }

        function bindCheckAll() {
            $(‘#idCheckAll‘).click(function () {
                $(‘#table_tb‘).find(‘:checkbox‘).each(function () {
                    // $(this)  = checkbox
                    if($(‘#idEditMode‘).hasClass(‘btn-warning‘)){
                        if($(this).prop(‘checked‘)){
                            // 当前行已经进入编辑模式了
                        }else{
                            // 进入编辑模式
                            var $currentTr = $(this).parent().parent();
                            trIntoEditMode($currentTr);
                            $(this).prop(‘checked‘,true);
                        }
                    }else{
                        $(this).prop(‘checked‘,true);
                    }
                })
            })
        }

        function bindEditMode() {
            $(‘#idEditMode‘).click(function () {
                var editing = $(this).hasClass(‘btn-warning‘);
                if(editing){
                    // 退出编辑模式
                    $(this).removeClass(‘btn-warning‘);
                    $(this).text(‘进入编辑模式‘);

                    $(‘#table_tb‘).find(‘:checked‘).each(function () {
                        var $currentTr = $(this).parent().parent();
                        trOutEditMode($currentTr);
                    })

                }else{
                    // 进入编辑模式
                    $(this).addClass(‘btn-warning‘);
                    $(this).text(‘退出编辑模式‘);
                    $(‘#table_tb‘).find(‘:checked‘).each(function () {
                        var $currentTr = $(this).parent().parent();
                        trIntoEditMode($currentTr);
                    })
                }
            })
        }

        function bindCheckbox() {
            // $(‘#table_tb‘).find(‘:checkbox‘).click()
            $(‘#table_tb‘).on(‘click‘,‘:checkbox‘,function () {

                if($(‘#idEditMode‘).hasClass(‘btn-warning‘)){
                    var ck = $(this).prop(‘checked‘);
                    var $currentTr = $(this).parent().parent();
                    if(ck){
                        // 进入编辑模式
                        trIntoEditMode($currentTr);
                    }else{
                        // 退出编辑模式
                        trOutEditMode($currentTr)
                    }
                }
            })
        }

        function trIntoEditMode($tr) {
            $tr.addClass(‘success‘);
            $tr.attr(‘has-edit‘,‘true‘);
            $tr.children().each(function () {
                // $(this) => td
                var editEnable = $(this).attr(‘edit-enable‘);
                var editType = $(this).attr(‘edit-type‘);
                if(editEnable==‘true‘){
                    if(editType == ‘select‘){
                        var globalName = $(this).attr(‘global-name‘); //  "device_status_choices"
                        var origin = $(this).attr(‘origin‘); // 1
                        // 生成select标签
                        var sel = document.createElement(‘select‘);
                        sel.className = "form-control";
                        $.each(window[globalName],function(k1,v1){
                            var op = document.createElement(‘option‘);
                            op.setAttribute(‘value‘,v1[0]);
                            op.innerHTML = v1[1];
                            $(sel).append(op);
                        });
                        $(sel).val(origin);

                        $(this).html(sel);

                        // 下拉框
                        /*
                        *  <select>
                        *      <option value=‘1‘>在线</option>
                        *      <option value=‘2‘>下线</option>
                        *      <option value=‘3‘>离线</option>
                        *  </select>
                        *
                        * */
                        //  在线

                    }else if(editType == ‘input‘){
                        // input文本框
                        // *******可以进入编辑模式*******
                        var innerText = $(this).text();
                        var tag = document.createElement(‘input‘);
                        tag.className = "form-control";
                        tag.value = innerText;
                        $(this).html(tag);
                    }
                }
            })
        }

        function trOutEditMode($tr){
            $tr.removeClass(‘success‘);
            $tr.children().each(function () {
                // $(this) => td
                var editEnable = $(this).attr(‘edit-enable‘);
                var editType = $(this).attr(‘edit-type‘);
                if(editEnable==‘true‘){
                    if (editType == ‘select‘){
                        // 获取正在编辑的select对象
                        var $select = $(this).children().first();
                        // 获取选中的option的value
                        var newId = $select.val();
                        // 获取选中的option的文本内容
                        var newText = $select[0].selectedOptions[0].innerHTML;
                        // 在td中设置文本内容
                        $(this).html(newText);
                        $(this).attr(‘new-val‘,newId);

                    }else if(editType == ‘input‘) {
                        // *******可以退出编辑模式*******
                        var $input = $(this).children().first();
                        var inputValue = $input.val();
                        $(this).html(inputValue);
                        $(this).attr(‘new-val‘,inputValue);
                    }

                }
            })
        }

        String.prototype.format = function (kwargs) {
            // this ="laiying: {age} - {gender}";
            // kwargs =  {‘age‘:18,‘gender‘: ‘女‘}
            var ret = this.replace(/\{(\w+)\}/g,function (km,m) {
                return kwargs[m];
            });
            return ret;
        };

        function init(pager) {
            $.ajax({
                url: requestUrl,
                type: ‘GET‘,
                data: {‘pager‘:pager},
                dataType: ‘JSON‘,
                success:function (result) {
                    initGlobalData(result.global_dict);
                    initHeader(result.table_config);
                    initBody(result.table_config,result.data_list);
                    initPager(result.pager);
                }
            })

        }
        function initPager(pager){
            $(‘#idPagination‘).html(pager);
        }

        function initHeader(table_config) {
            /*
            table_config = [
                {
                    ‘q‘: ‘id‘,
                    ‘title‘: ‘ID‘,
                    ‘display‘:false
                },
                {
                    ‘q‘: ‘name‘,
                    ‘title‘: ‘随便‘,
                    ‘display‘: true
                }
            ]
             */

             /*
            <tr>
                <th>ID</th>
                <th>用户名</th>
            </tr>
            */
            var tr = document.createElement(‘tr‘);
            $.each(table_config,function (k,item) {
                if(item.display){
                    var th = document.createElement(‘th‘);
                    th.innerHTML = item.title;
                    $(tr).append(th);
                }

            });
            $(‘#table_th‘).empty();
            $(‘#table_th‘).append(tr);
        }

        function initBody(table_config,data_list){
            $(‘#table_tb‘).empty();
            for(var i=0;i<data_list.length;i++){
                var row = data_list[i];
                // row = {‘cabinet_num‘: ‘12B‘, ‘cabinet_order‘: ‘1‘, ‘id‘: 1},
                var tr = document.createElement(‘tr‘);
                tr.setAttribute(‘row-id‘,row[‘id‘]);
                $.each(table_config,function (i,colConfig) {
                   if(colConfig.display){
                       var td = document.createElement(‘td‘);
                       /* 生成文本信息 */
                       var kwargs = {};
                       $.each(colConfig.text.kwargs,function (key,value) {

                           if(value.substring(0,2) == ‘@@‘){
                               var globalName = value.substring(2,value.length); // 全局变量的名称
                               var currentId = row[colConfig.q]; // 获取的数据库中存储的数字类型值
                               var t = getTextFromGlobalById(globalName,currentId);
                               kwargs[key] = t;
                           }
                           else if (value[0] == ‘@‘){
                                kwargs[key] = row[value.substring(1,value.length)]; //cabinet_num
                           }else{
                                kwargs[key] = value;
                           }
                       });
                       var temp = colConfig.text.content.format(kwargs);
                       td.innerHTML = temp;

                       /* 属性colConfig.attrs = {‘edit-enable‘: ‘true‘,‘edit-type‘: ‘select‘}  */
                        $.each(colConfig.attrs,function (kk,vv) {
                            if(vv[0] == ‘@‘){
                                td.setAttribute(kk,row[vv.substring(1,vv.length)]);
                            }else{
                                td.setAttribute(kk,vv);
                            }
                        });

                       $(tr).append(td);
                   }
                });

                $(‘#table_tb‘).append(tr);
            }
        }

        function initGlobalData(global_dict) {
            $.each(global_dict,function (k,v) {
                // k = "device_type_choices"
                // v= [[0,‘xx‘],[1,‘xxx‘]]
                // device_type_choices = 123;
                window[k] = v;
            })
        }

        function getTextFromGlobalById(globalName,currentId) {
            // globalName = "device_type_choices"
            // currentId = 1
            var ret = null;
            $.each(window[globalName],function (k,item) {
                if(item[0] == currentId){
                    ret = item[1];
                    return
                }
            });
            return ret;
        }

        jQuery.extend({
            ‘NB‘: function (url) {
                requestUrl = url;
                init();
                bindEditMode();
                bindCheckbox();
                bindCheckAll();
                bindCancelAll();
                bindReverseAll();
                bindSave();
                bindChangePager();
            },
            ‘changePager‘: function (num) {
                init(num);
            }
        })
})();

nbList.js

from django.shortcuts import render,HttpResponse
from django.views import View
import json

class AssetView(View):

    def get(self,request,*args,**kwargs):
        # 数据库中获取数据
        return render(request,‘asset.html‘)

class AssetJsonView(View):
    def get(self,request,*args,**kwargs):
        # 数据库中获取数据
        table_config = [
            {
                ‘q‘: None,
                ‘title‘: "选项",
                ‘display‘: True,
                ‘text‘: {‘content‘: "<input type=‘checkbox‘ />","kwargs": {}},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘id‘,
                ‘title‘: ‘ID‘,
                ‘display‘: False,
                ‘text‘:{},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘device_type_id‘,
                ‘title‘: ‘资产类型‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@@device_type_choices"}},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘device_status_id‘,
                ‘title‘: ‘状态‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@@device_status_choices"}},
                ‘attrs‘: {‘name‘:‘device_status_id‘,‘origin‘:"@device_status_id",‘edit-enable‘: ‘true‘, ‘edit-type‘: ‘select‘,"global-name": ‘device_status_choices‘}
            },
            {
                ‘q‘: ‘idc__id‘,
                ‘title‘: ‘IDC‘,
                ‘display‘: False,
                ‘text‘: {},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘idc__name‘,
                ‘title‘: ‘IDC‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@idc__name"}},
                ‘attrs‘: {‘name‘:‘idc_id‘,‘origin‘:"@idc__id",‘edit-enable‘: ‘true‘, ‘edit-type‘: ‘select‘,"global-name": ‘idc_choices‘}
            },
            {
                ‘q‘: ‘cabinet_order‘,
                ‘title‘: ‘机柜位置‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}",‘kwargs‘: {‘n‘: "@cabinet_order"}},
                ‘attrs‘: {‘name‘:‘cabinet_order‘,‘origin‘:"@cabinet_order",‘edit-enable‘: ‘true‘, ‘edit-type‘: ‘input‘}
            },
            {
                ‘q‘: ‘cabinet_num‘,
                ‘title‘: ‘机柜号‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@cabinet_num"}},
                ‘attrs‘: {},
            },
            {
                ‘q‘: None,
                ‘title‘: ‘操作‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "<a href=‘/assetdetail-{m}.html‘>{n}</a>", ‘kwargs‘: {‘n‘: ‘查看详细‘,‘m‘: ‘@id‘}},
                ‘attrs‘: {},
            }
        ]

        q_list = []
        for i in table_config:
            if not i[‘q‘]:
                continue
            q_list.append(i[‘q‘])

        from repository import models
        # 分页组件用户获取数据
        data_list = models.Asset.objects.all().values(*q_list)
        data_list = list(data_list)

        result = {
            ‘table_config‘:table_config,
            ‘data_list‘:data_list,
            ‘global_dict‘: {
                ‘device_type_choices‘: models.Asset.device_type_choices,
                ‘device_status_choices‘: models.Asset.device_status_choices,
                ‘idc_choices‘: list(models.IDC.objects.values_list(‘id‘,‘name‘))
            },
            # 分页组件生成页码信息
            ‘pager‘: """<li><a>1</a></li><li><a>2</a></li><li><a>3</a></li><li><a>4</a></li><li><a>5</a></li>"""

        }
        return HttpResponse(json.dumps(result))

    def put(self,request,*args,**kwargs):
        content = request.body
        v = json.loads(str(content,encoding=‘utf-8‘))
        print(v)
        ret = {
            ‘status‘:True
        }
        return HttpResponse(json.dumps(ret))

class BuinessUnitView(View):

    def get(self,request,*args,**kwargs):
        # 数据库中获取数据
        return render(request,‘business_unit.html‘)

class BuinessUnitJsonView(View):
    def get(self,request,*args,**kwargs):
        # 数据库中获取数据
        table_config = [
            {
                ‘q‘: None,
                ‘title‘: "选项",
                ‘display‘: True,
                ‘text‘: {‘content‘: "<input type=‘checkbox‘ />","kwargs": {}},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘id‘,
                ‘title‘: ‘ID‘,
                ‘display‘: False,
                ‘text‘:{},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘name‘,
                ‘title‘: ‘业务线名称‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@name"}},
                ‘attrs‘: {‘edit-enable‘:‘true‘,‘edit-type‘:‘input‘,‘origin‘: ‘@name‘}
            },
            {
                ‘q‘: ‘contact_id‘,
                ‘title‘: ‘联系人组‘,
                ‘display‘: False,
                ‘text‘: {},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘contact__name‘,
                ‘title‘: ‘联系人组‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@contact__name"}},
                ‘attrs‘: {‘edit-enable‘:‘true‘,‘edit-type‘:‘select‘,‘origin‘: ‘@contact_id‘,"global-name": ‘contact_choices‘}
            },
            {
                ‘q‘: ‘manager__name‘,
                ‘title‘: ‘管理员组‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@manager__name"}},
                ‘attrs‘: {}
            },
            {
                ‘q‘: None,
                ‘title‘: ‘操作‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "<a href=‘/assetdetail-{m}.html‘>{n}</a>", ‘kwargs‘: {‘n‘: ‘查看详细‘,‘m‘: ‘@id‘}},
                ‘attrs‘: {},
            }
        ]

        q_list = []
        for i in table_config:
            if not i[‘q‘]:
                continue
            q_list.append(i[‘q‘])

        from repository import models

        data_list = models.BusinessUnit.objects.all().values(*q_list)
        data_list = list(data_list)

        result = {
            ‘table_config‘:table_config,
            ‘data_list‘:data_list,
            ‘global_dict‘: {
                # ‘device_type_choices‘: models.Asset.device_type_choices,
                # ‘device_status_choices‘: models.Asset.device_status_choices,
                # ‘idc_choices‘: list(models.IDC.objects.values_list(‘id‘,‘name‘))
                ‘contact_choices‘:list(models.UserGroup.objects.values_list(‘id‘,‘name‘))
            },
            ‘pager‘: """<li><a>1</a></li><li><a>2</a></li><li><a>3</a></li><li><a>4</a></li><li><a>5</a></li>"""

        }
        return HttpResponse(json.dumps(result))

    def put(self,request,*args,**kwargs):
        content = request.body
        v = json.loads(str(content,encoding=‘utf-8‘))
        print(v)
        ret = {
            ‘status‘:True
        }
        return HttpResponse(json.dumps(ret))

views

原文地址:https://www.cnblogs.com/jintian/p/11297764.html

时间: 2024-10-11 15:02:46

CMDB项目CURD组件进入编辑模式的相关文章

CMDB项目CURD组件之全选取消反选和编辑模式

$(':checked') 选中的所有元素 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css

CMDB项目CURD组件之基于jQuery扩展封装组件

request.body from django.shortcuts import render,HttpResponse from django.views import View import json class AssetView(View): def get(self,request,*args,**kwargs): # 数据库中获取数据 return render(request,'asset.html') class AssetJsonView(View): def get(sel

CMDB项目CURD组件之搜索功能介绍

#!/usr/bin/env python # -*- coding:utf-8 -*- import json from django.db.models import Q from repository import models from utils.pager import PageInfo from utils.response import BaseResponse from django.http.request import QueryDict from .base import

CMDB项目CURD组件之自定义td属性

from django.shortcuts import render,HttpResponse from django.views import View import json class AssetView(View): def get(self,request,*args,**kwargs): # 数据库中获取数据 return render(request,'asset.html') class AssetJsonView(View): def get(self,request,*ar

CMDB项目CURD组件之分页功能

原文地址:https://www.cnblogs.com/jintian/p/11300546.html

基于vue项目的组件中导入mui框架初始化滑动等效果时需移除严格模式的问题

基于vue项目的组件中导入mui框架初始化滑动等效果时,控制台报错:Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them 可使用 babel-plugin -transform-remove-strict-mode 移除严格模式 可先进行$ n

IOS开发——UI进阶篇(四)全局刷新,局部刷新,左滑操作,左滑出现更多按钮,进入编辑模式,批量删除,自定义批量删除

首先创建项目,在storyboard如下布局控件,设置好约束 然后创建cell模型类XMGWineCell数据模型类XMGWine创建UITableView,设置数据源协议,实现数据源方法懒加载数据这些在前面已经做过很多次了,代码就不一一写了 一.全局刷新 1.添加单组数据并全局刷新 - (IBAction)add { // 添加模型数据 XMGWine *wine = [[XMGWine alloc] init]; wine.money = @"20.5"; wine.name =

easyui-datagrid 编辑模式详解

   一,建立编辑器 从api得知,扩展一种新的编辑器类型,需要提供以上几个方法.项目中正好需要一个checkbox 类型编辑器,但在easyui中并没提供这样的编辑器,那我们可以通过扩展编辑器来解决,扩展如下 1 $.extend($.fn.datagrid.defaults.editors, { 2 checkbox: {//调用名称 3 init: function (container, options) { 4 //container 用于装载编辑器 options,提供编辑器初始参数

技巧:Vim 的纵向编辑模式

https://www.ibm.com/developerworks/cn/linux/l-cn-vimcolumn/ 开始之前 人类大脑对文字的处理是平面式的,所以我们浏览文章.查找资料或者重构代码,要么是横向读,要么是纵向读,要么使用搜索功能,将文字作为一个平面整体.而在编辑文字.编写代码的时候则不是横向就是纵向.常规文本编辑器都是横向编辑,而纵向编辑也常被作为特色功能.比如 Vim.EditPlus.UltraEdit 这些编辑器都有纵向编辑模式,或者称为列模式.像日常文字处理工具 Mic