【实战】AJAX之『后台列表管理模块』

知识补充

  1. caption:标题标签
  2. border-collapse:collapse去除双边框
  3. table显示:display-table
  4. text-decoration:none 去除文本默认样式
  5. .clearfix::after{content=’’, display=‘table’, clear:both}:清除浮动
  6. 布局方式:thead-tbody-tfoot
  7. setselectionRange(star, over):选中输入框中的文字
; (function (doc) {

    var oNav = doc.getElementsByClassName('J_nav')[0],
        oNavItems = oNav.getElementsByClassName('nav-item'),
        oSearchRow = doc.getElementsByClassName('J_searchRow')[0],
        oWarningTip = doc.getElementsByClassName('J_tipRow')[0],
        oCourseList = doc.getElementsByClassName('J_courseList')[0],
        oSearchInput = doc.getElementById('J_searchInput'),
        oPageBtnRow = doc.getElementsByClassName('J_pageBtnRow')[0],
        oPageBtnList = doc.getElementsByClassName('J_pageBtnList')[0],
        oBtnItems = doc.getElementsByClassName('btn-item'),
        oCourseInputs = doc.getElementsByClassName('course-name-input'),
        oCourseSpans = oCourseList.getElementsByClassName('course-name'),

        listItemTpl = doc.getElementById('J_listItemTpl').innerHTML,
        pageBtnItemTpl = document.getElementById('J_pageBtnItemTpl').innerHTML,

        oNavItemLen = oNavItems.length;

    var field = 'manage',
        pageNum = 0,
        curId = 0,
        curIdx = -1;

    var API = {
        getCourseList: 'http://localhost/api_for_study/index.php/List/getCourseListForManage',
        getSearchList: 'http://localhost/api_for_study/index.php/List/getSearchListForManage',
        doListItem: 'http://localhost/api_for_study/index.php/List/doListItemForManage',
        updateCourseName: 'http://localhost/api_for_study/index.php/List/updateCourseNameForManage'
    }

    var init = function () {
        getCourseList(field, pageNum);
        bindEvent();
    }

    function bindEvent() {
        oNav.addEventListener('click', navClick, false);
        oSearchInput.addEventListener('input', throttle(courseSearch, 1000), false);
        oPageBtnList.addEventListener('click', changePage, false);
        oCourseList.addEventListener('click', listClick, false);
    }

    function showWarningTip(show) {
        if (show) {
            oCourseList.innerHTML = '';
            oWarningTip.className = 'tip-row J_tipRow';
        } else {
            oWarningTip.className += ' hide';
        }
    }

    function showSearchInput(show) {
        if (show) {
            oSearchRow.className += ' show';
        } else {
            oSearchRow.className = 'search-row J_searchRow';
        }
    }

    function showPageBtnRow(show) {
        if (show) {
            oPageBtnRow.className += ' show'
        } else {
            oPageBtnRow.className = 'page-btn-row J_pageBtnRow'
        }
    }

    function navClick(e) {
        var e = e || window.event,
            tar = e.target || e.srcElement,
            className = tar.className;

        e.stopPropagation();

        if (className === 'nav-lk') {
            var oParent = tar.parentNode,
                item;

            field = oParent.getAttribute('data-field');

            for (var i = 0; i < oNavItemLen; i++) {
                item = oNavItems[i];
                item.className = 'nav-item';
            }
            oParent.className += ' active';

            if (field === 'search') {
                showWarningTip(true);
                showSearchInput(true);
                showPageBtnRow(false);
                return;
            }

            pageNum = 0;
            getCourseList(field, pageNum);
        }
    }

    function changePage(e) {
        var e = e || window.event,
            tar = e.target || e.srcElement,
            className = tar.className;

        e.stopPropagation();

        if (className = 'page-btn') {
            var oParent = tar.parentNode,
                oBtnItemsLen = oBtnItems.length,
                item;

            pageNum = Array.prototype.indexOf.call(oBtnItems, oParent);

            for (var i = 0; i < oBtnItemsLen; i++) {
                item = oBtnItems[i];
                item.className = 'btn-item';
            }

            // oParent.className = 'btn-item cur'; 
            getCourseList(field, pageNum)
        }
    }

    function listClick(e) {
        var e = e || window.event,
            tar = e.target || e.srcElement,
            className = tar.className,
            itemId = tar.getAttribute('data-id');

        e.stopPropagation();

        switch (className) {
            case 'list-btn delete':
                var c = confirm('确认删除');
                c && doListItem('remove', pageNum, itemId);
                break;
            case 'list-btn regain':
                var c = confirm('确认恢复');
                c && doListItem('regain', pageNum, itemId);
                break;
            case 'course-name':
                showInput(tar)
                break;
            default:
                break;
        }
    }

    function showInput(target) {
        var oParent = target.parentNode,
            thisInput = oParent.getElementsByClassName('course-name-input')[0],
            thisInputLen = thisInput.value.length;

        curId = thisInput.getAttribute('data-id');
        curIdx = [].indexOf.call(oCourseInputs, thisInput);

        hideAllInputs();
        thisInput.className += ' show';
        thisInput.focus();
        thisInput.setSelectionRange(0, thisInputLen);

        document.addEventListener('click', updateCourseName, false);
        document.addEventListener('keyup', updateCourseName, false);
    }

    function hideAllInputs() {
        var inputsLen = oCourseInputs.length,
            item;

        for (var i = 0; i < inputsLen; i++) {
            item = oCourseInputs[i];
            item.className = 'course-name-input';
            item.blur();
        }

        document.removeEventListener('click', updateCourseName, false);
        document.removeEventListener('keyup', updateCourseName, false);
    }

    function updateCourseName(e) {
        var e = e || window.event,
            eventType = e.type;

        if (eventType === 'keyup') {
            var keyCode = e.keyCode;
            if (keyCode === 13) {
                submitNewCourseName(curId, curIdx);
            }
            return;
        }
        submitNewCourseName(curId, curIdx);
    }

    function submitNewCourseName(curId, curIdx) {
        hideAllInputs();
        var newVal = oCourseInputs[curIdx].value,
            thisCourseSpan = oCourseSpans[curIdx];

        if (newVal !== thisCourseSpan.innerHTML) {
            xhr.ajax({
                url: API.updateCourseName,
                type: 'POST',
                dataType: 'JSON',
                data: {
                    itemId: curId,
                    newVal: newVal
                },
                success: function (data) {
                    if (data === 'success') {
                        thisCourseSpan.innerHTML = newVal;
                    } else {
                        console.log(data);
                        console.log(curId, newVal);

                        alert('更改课程名称失败,请重试哈');
                    }
                    curId = 0;
                    curIdx = -1;
                },
                error: function () {
                    alert('更改课程名称失败,请重试');
                }
            })
        }
    }


    // 没有field,后端怎么知道该返回manage数据还是trash数据? 删除操作 -> manage、恢复操作 -> trash
    // 选择删除/恢复操作后还要告诉后端删除/恢复第几个,返回第几页
    function doListItem(type, pageNum, itemId) {
        xhr.ajax({
            url: API.doListItem,
            type: 'POST',
            dataType: 'JSON',
            data: {
                type: type,
                pageNum: pageNum,
                itemId: itemId
            },
            success: function (data) {
                var res = data.res,
                    pageCount = data.pages;

                _setDatas(field, res, pageCount, pageNum);
            },
            error: function () {
                alert('操作列表失败,请重试!');
            }
        })
    }


    function getCourseList(field, pageNum) {
        xhr.ajax({
            url: API.getCourseList,
            type: 'POST',
            dataType: 'JSON',
            data: {
                field: field,
                pageNum: pageNum
            },
            success: function (data) {
                var res = data.res,
                    pageCount = data.pages;

                _setDatas(field, res, pageCount, pageNum);
            },
            error: function () {
                alert('列表获取失败,请重试!');
            }
        })
    }

    function courseSearch(e) {
        var e = e || window.event,
            val = trimSpace(this.value),
            valLen = val.length;

        e.stopPropagation();

        if (valLen > 0) {
            getSearchList(val);
        } else {
            showWarningTip(true);
        }
    }

    function getSearchList(keyword) {
        xhr.ajax({
            url: API.getSearchList,
            type: 'POST',
            dataType: 'JSON',
            data: {
                keyword: keyword
            },
            success: function (data) {
                var res = data.res,
                    pageCount = data.pages;

                _setDatas('manage', res);
            },
            error: function () {
                alert('搜索操作失败,请重试!');
            }
        })
    }

    // 每次渲染列表的时候都要重新获取页数,因为列表删除后再重新获取会影响分页器页数
    function _setDatas(field, data, pageCount, pageNUm) {
        if (data && data.length > 0) {
            oCourseList.innerHTML = renderList(field, data);
            showWarningTip(false);

            if (pageCount > 1 && field !== 'search') {
                oPageBtnList.innerHTML = renderPageBtns(pageCount, pageNum);
                showPageBtnRow(true);
            } else {
                oPageBtnList.innerHTML = '';
                showPageBtnRow(false);
            }
        } else {
            showWarningTip(true);
        }
    }

    function renderList(listField, data) {
        var list = ''

        data.forEach(function (elem) {
            list += listItemTpl.replace(/{{(.*?)}}/g, function (node, key) {
                return {
                    id: elem.id,
                    course: elem.course,
                    hour: elem.hour,
                    teacher: elem.teacher,
                    field: elem.field,
                    type: listField == 'trash' ? 'regain' : 'delete',
                    typeText: listField == 'trash' ? '恢复' : '删除'
                }[key]
            })
        })

        return list;
    }

    function renderPageBtns(pageCount, pageNum) {
        var list = '';

        for (var i = 0; i < pageCount; i++) {
            list += pageBtnItemTpl.replace(/{{(.*?)}}/g, function (node, key) {
                return {
                    pageNum: i + 1,
                    isCur: i == pageNum && 'cur'
                }[key];
            });
        }

        return list;
    }

    init();

})(document);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值