1. 程式人生 > 其它 >jq ajax獲取資料動態新增,each遍歷不到問題

jq ajax獲取資料動態新增,each遍歷不到問題

技術標籤:前端jquery

問題描述:使用ajax獲取資料動態新增,使用each遍歷不到
問題原因:載入順序問題,ajax還沒執行完就使用each遍歷了,肯定遍歷不到
解決辦法:在ajax執行成功後呼叫遍歷的函式(在success裡呼叫)

var page = {
    sTable:'',
    cTable:'',
    fixedHeaderOffset:0,
    init: function () { //頁面初始化方法
        this.initProject();
    },

  //專案範圍
initProject:function () {
    //獲取專案
    $('#select-project').click(function () {
        if(!validate()) return ;

        var msg = tmpl("projectselector_tmpl", {
            selectMode: 0
        });

        bootbox.dialog({
            message: msg,
            title: "選擇專案",
            onEscape: true,
            backdrop: true
        });
        // 搜尋使用者
        searProject();

        //專案是否已選擇 
       //isCheckedProject(); //最開始是在這裡呼叫檢查專案(是否已選,已選就選上),由於searProject()是使用ajax請求資料並新增資料,此時呼叫searProject(),ajax還沒執行到。在success裡呼叫isCheckedProject()解決問題

        //切換房源型別
        $(document).on("click","#projectTableContainer .header ul li",selectType);

        //選擇/取消選擇專案
        $(document).on("click","#projectTableContainer table tbody tr",function () {
            if($(this).hasClass('checked')){
                $(this).removeClass('checked');
                $(this).find('.is-selected').text('');
            }else{
                $(this).addClass('checked');
                $(this).find('.is-selected').text('√');
            }
        });

        //全選專案
        $(document).on("click","#projectTableContainer .footer .select-all",function () {
            $('#projectTableContainer table tbody tr').each(function (i,o) {
                $(o).addClass('checked');
                $(o).find('.is-selected').text('√');
            });
        });

        //取消全選
        $(document).on("click","#projectTableContainer .footer .cancel-all",function () {
            $('#projectTableContainer table tbody tr').each(function (i,o) {
                $(o).removeClass('checked');
                $(o).find('.is-selected').text('');
            });
        });

        //確定選擇,新增已選專案到專案範圍
        $(document).on("click","#projectTableContainer .footer .select-project-btn",function () {
            var projectsContainer = $('#projects');
            $('#projectTableContainer table tbody tr').each(function (i,o) {
                if($(o).hasClass('checked')){
                    var data = $(o).data('project');
                    var item = '<div class="project-item"><span class="rm-item">x</span>'+data.name+'<input type="hidden" name="project_id[]" value="'+data.id+'"></div>'
                    projectsContainer.append(item);
                }
            });

            bootbox.hideAll();
        });

        //取消選擇
        $(document).on("click","#projectTableContainer .footer .cancel-project-btn",function () {
            bootbox.hideAll();
        });

    });

    //驗證公司、使用者是否為空
    var validate = function(){
        var customer_id = $('#customer_id').val();
        var company_code = $('#company_code').val();
        var type = $('input[name="type"]:checked').val();
        var submit = true;
        var errortxt = '';
        if(type==2 && utils.isEmpty(company_code)){
            submit = false;
            errortxt += '請先選擇企業';
        }
        if(utils.isEmpty(customer_id)){
            submit = false;
            errortxt += utils.isEmpty(errortxt) ? '請先選擇使用者': '<br/>請先選擇使用者';
        }
        if(!submit){
            $('#hid_select-project').html(errortxt);
            return false;
        }
        $('#hid_select-project').html(''); //已選擇資訊清空提示資訊
        return true;
    };

    var projectTable = null;
    //查詢使用者資訊
    var keyupHandle;
    var searProject = function () {
        var customer_id = $('#customer_id').val();
        var company_code = $('#company_code').val();
        var type = $('input[name="type"]:checked').val();
        var noDataTxt = utils.isEmpty(company_code)? '沒有查詢到專案,請重新選擇使用者': '沒有查詢到專案,請重新選擇企業或使用者';
        keyupHandle && clearTimeout(keyupHandle);
        keyupHandle = setTimeout(function () {
            if (!utils.isEmpty(customer_id)) {
                App.blockUI({
                    target: "#projectTableContainer",
                    message: "載入中..."
                });
                $.ajax({
                    type: "GET",
                    url: "/collection/query-projects",
                    data: {
                        customer_id: customer_id,
                        company_code: company_code,
                        type: type,
                    },
                    success: function (data) {
                        App.unblockUI("#projectTableContainer");

                        projectTable && projectTable.destroy();

                        var projectDataHTML = tmpl("project_data_tmpl", {
                            projects: data
                        });

                        $("#projectTableContainer").html(projectDataHTML);
                        projectTable = $('#projectTable').DataTable({
                            paging: false,
                            searching: false,
                            ordering: false,
                            info: false,
                            language: {
                                emptyTable: noDataTxt,
                            },
                        });
                        //開始是放在外面的
                        //專案是否已選擇
                        isCheckedProject();
                    },
                    error: function () {
                        App.unblockUI("#projectTableContainer");
                        $("#userTableContainer").html('<div class="text-center">伺服器異常,請稍後再試</div>');
                    }
                });
            } else {
                projectTable && projectTable.destroy();

                var projectDataHTML = tmpl("project_data_tmpl", {
                    projects: []
                });

                $("#projectTableContainer").html(projectDataHTML);
                    projectTable = $('#projectTable').DataTable({
                    responsive: true,
                    paging: false,
                    searching: false,
                    ordering: false,
                    info: false,
                    language: {
                        emptyTable: noDataTxt,
                    }
                });
            }
        }, 200);
    };

    //切換專案類別
    var selectType = function(){
        $(this).parent().children('li').removeClass('active');
        $(this).addClass('active');
        var type = $(this).data('type');
        $('#projectTable tbody tr').each(function (i,o) {
            if($(o).hasClass(type)){
                $(o).show();
            }else{
                $(o).hide();
            }
        });
    };

    //是否存在已選專案
    var isCheckedProject = function(){
        var projectIds = [];
        $('input[name="project_id[]"]').each(function (i,o) {
            projectIds.push($(o).val());
        })
        if(projectIds.length>0){
            console.log(projectIds);
            console.log($('#projectTableContainer table tbody tr'));

            $('#projectTableContainer table tbody tr').each(function (i,o) {
                var data = $(o).data('project');
                console.log(data);
                if($.inArray(data.id,projectIds)!=-1){
                    $(o).addClass('checked');
                    $(o).find('.is-selected').text('√');
                }
            });
        }
    };

    //刪除專案
    $('.select-project-list').on('click','.project-item .rm-item',function () {
        $(this).parent().remove();
    });
},

}

page.init();

html

<!--專案-->
<script type="text/html" id="projectselector_tmpl">
    <div class="row">
        <div class="col-md-12" id="projectTableContainer"></div>
    </div>
</script>

<script type="text/html" id="project_data_tmpl">
    <div class="header">
        <ul>
            <?php foreach ($dept as $k=>$item){ ?>
                <li data-type="<?=$item['id']?>"><?=$item['alia_name']?></li>
            <?php } ?>
        </ul>
    </div>
    <table class="table table-bordered table-hover" id="projectTable" style="width:100%;">
        <thead>
        <tr>
            <th data-priority="1">專案名稱</th>
            <th data-priority="2">選擇</th>
        </tr>
        </thead>
        <tbody>
        <% for(var n in projects) {
        var project = projects[n];
        %>
        <tr data-project='<%=JSON.stringify(project)%>' id="<%=project.id || ''%>" class="<%=project.dept_id || ''%>">
            <td><%=project.name || ""%></td>
            <td class="is-selected"></td>
        </tr>
        <% } %>
        </tbody>
    </table>

    <div class="footer">
        <div class="radio-box">
            <div class="btn radio select-all">全部專案</div>
            <div class="btn radio cancel-all">取消全選</div>
        </div>
        <div class="foot-btn">
            <button type="button" class="btn select-project-btn">確定選擇</button>
            <button type="button" class="btn default cancel-project-btn">取消選擇</button>
        </div>
    </div>
</script>