简体   繁体   English

在 jQuery 中发出 Ajax 请求时,事件仅触发一次

[英]Event only fires once when making Ajax request in jQuery

I have a couple of drop downs that are populated from SharePoint using SPServices.我有几个使用 SPServices 从 SharePoint 填充的下拉列表。 This part works great.这部分效果很好。 But then, I have a button that on click loads data from SharePoint and uses the dropdown texts as filter to fetch the data that will populate a table using the DataTables plugin.但是,我有一个按钮,单击该按钮即可从 SharePoint 加载数据,并使用下拉文本作为过滤器来获取将使用 DataTables 插件填充表格的数据。 This part works only once;这部分只工作一次; if I click the button again, nothing happens.如果我再次单击该按钮,则没有任何反应。

This is how I populate the dropdowns:这就是我填充下拉列表的方式:

$(document).ready(function () {
var theYear; // Selected Year
var theRO; // Selected RO
//Fills the Dropdown lists (Year and RO)
$().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "{ListID}",
    CAMLViewFields: "<ViewFields><FieldRef Name='Fiscal_x0020_Year' /><FieldRef    Name='Regional_x0020_Office' /></ViewFields>",
    completefunc: function (xData, Status) {
        //Add Select Value option
        $("#dropdown").prepend($('<option>', {
            value: '',
            text: 'Select Fiscal Year'
        }));
        $("#dropdownRO").prepend($('<option>', {
            value: '',
            text: 'Select Regional Office'
        }));
        //Fetching Data from SharePoint    
        $(xData.responseXML).SPFilterNode("z:row").each(function () {
            var dropDown = "<option value='" + $(this).attr("ows_Fiscal_x0020_Year") + "'>" + $(this).attr("ows_Fiscal_x0020_Year") + "</option>";
            var dropDownRO = "<option value='" + $(this).attr("ows_Regional_x0020_Office") + "'>" + $(this).attr("ows_Regional_x0020_Office") + "</option>";
            $("#dropdown").append(dropDown);
            $("#dropdownRO").append(dropDownRO);
            /////////////Deletes duplicates from dropdown list////////////////
            var usedNames = {};
            $("#dropdown > option, #dropdownRO > option").each(function () {
                if (usedNames[this.text]) {
                    $(this).remove();
                } else {
                    usedNames[this.text] = this.value;
                }
            });
            ////Deletes repeated rows from table
            var seen = {};
            $('#myTable tr, #tasksUL li, .dropdown-menu li').each(function () {
                var txt = $(this).text();
                if (seen[txt]) $(this).remove();
                else seen[txt] = true;
            });
        });
    } //end of completeFunc
}); //end of SPServices
$('.myButton').on('click', function () {
    run()
});
}); //End jQuery Function

This is the function I need to run every time I click on "myButton" after changing my selection in the dropdowns:这是我在更改下拉列表中的选择后每次单击“myButton”时需要运行的功能:

        function run() {

theYear = $('#dropdown option:selected').text(); // Selected Year
theRO = $('#dropdownRO option:selected').text(); // Selected RO
var call = $.ajax({
    url: "https://blah-blah-blah/_api/web/lists/getByTitle('Consolidated%20LC%20Report')/items()?$filter=Fiscal_x0020_Year%20eq%20'" + theYear + "' and Regional_x0020_Office eq '" + theRO + "'&$orderby=Id&$select=Id,Title,Fiscal_x0020_Year,Notices_x0020_Received,Declined_x0020_Participation,Selected_x0020_Field_x0020_Revie,Selected_x0020_File_x0020_Review,Pending,Pending_x0020_Previous_x0020_Yea,Controversial,GFP_x0020_Reviews,NAD_x0020_Appeals,Mediation_x0020_Cases,Monthly_x0020_Cost_x0020_Savings,Monthly_x0020_Expenditure,Regional_x0020_Office,Month_Number", //Works, filters added
    type: "GET",
    cache: false,
    dataType: "json",
    headers: {
        Accept: "application/json;odata=verbose",
    }
}); //End of ajax function///
call.done(function (data, textStatus, jqXHR) {
    var oTable = $('#example').dataTable({
        "aLengthMenu": [
            [25, 50, 100, 200, -1],
            [25, 50, 100, 200, "All"]
        ],
            "iDisplayLength": -1, //Number of rows by default. -1 means All Records
        "sPaginationType": "full_numbers",
            "aaData": data.d.results,
            "bJQueryUI": false,
            "bProcessing": true,
            "aoColumns": [{
            "mData": "Id",
            "bVisible": false
        }, //Invisible column
        {
            "mData": "Title"
        }, {
            "mData": "Notices_x0020_Received"
        }, {
            "mData": "Declined_x0020_Participation"
        }, {
            "mData": "Selected_x0020_Field_x0020_Revie"
        }, {
            "mData": "Selected_x0020_File_x0020_Review"
        }, {
            "mData": "Pending"
        }, {
            "mData": "Pending_x0020_Previous_x0020_Yea"
        }, {
            "mData": "Controversial"
        }, {
            "mData": "GFP_x0020_Reviews"
        }, {
            "mData": "NAD_x0020_Appeals"
        }, {
            "mData": "Mediation_x0020_Cases"
        }, {
            "mData": "Monthly_x0020_Cost_x0020_Savings",
            "fnRender": function (obj, val) {
                return accounting.formatMoney(val);
            }
        }, {
            "mData": "Monthly_x0020_Expenditure",
            "fnRender": function (obj, val) {
                return accounting.formatMoney(val);
            }
        }],
            "bDeferRender": true,
        "bRetrieve": true,
        "bInfo": true,
        "bAutoWidth": true,
        "bDestroy": true,
            "sDom": 'T&;"clear"&;frtip',
            "oTableTools": {
            "aButtons": ["xls"],
                "sSwfPath": "../../Style Library/js/datatables/TableTools/media/swf/copy_csv_xls_pdf.swf",
        },
            "sSearch": "Filter",
            "fnDrawCallback": function () {
            //Add totals row
            var Columns = $("#example > tbody").find("> tr:first > td").length;
            $('#example tr:last').after('<tr><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td></tr>');
            //Formating the Total row number to no decimals
            $("#example tr:last td:not(:first,:last)").text(function (i) {
                var t = 0;
                $(this).parent().prevAll().find("td:nth-child(" + (i + 2) + ")").each(function () {
                    t += parseFloat($(this).text().replace(/[\$,]/g, '') * 1);
                });
                return parseInt(t * 100, 10) / 100;
            });
            //Format the monthly expenditure and savings to currency formatFormating the currency
            var cell = new Array();
            cell[0] = $('#example tr:last td:nth-child(12)').text();
            cell[1] = $('#example tr:last td:nth-child(13)').text();
            $('#example tr:last').find('td:nth-child(12)').html(accounting.formatMoney(cell[0]));
            $('#example tr:last').find('td:nth-child(13)').html(accounting.formatMoney(cell[1]));
            $('#example tr:last').find('td:last').hide();
        } //hides extra td that was showing
    }); //End of Datatable()
}); //End of call.done function
$('#theTableDiv').slideDown();
} //end of run() function

I'm not a programmer, I'm just trying to learn.我不是程序员,我只是想学习。 I would appreciate any help.我将不胜感激任何帮助。 Thanks in advance提前致谢

I would guess that you are replacing the part of the page where the button lives.我猜你正在替换按钮所在的页面部分。 (you really need to format your code more neatly for SO... use JSFiddle.net and their TidyUp button). (你真的需要更整洁地格式化你的代码......使用 JSFiddle.net 和他们的 TidyUp 按钮)。

If that is the case you need to use a delegated event handler :如果是这种情况,您需要使用委托的事件处理程序

$(document).on('click', '.myButton', function () {
    run()
});

This listens at a static ancestor of the desired node, then runs the selector when the event occurs, then it applies the function to any matching elements that caused the event.它侦听所需节点的静态祖先,然后在事件发生时运行选择器,然后将函数应用于导致事件的任何匹配元素。

document is the fallback parent if you don't have a convenient ancestor.如果您没有方便的祖先,则document是后备父级。 Do not use 'body' for delegated events as it has odd behaviour.不要将“body”用于委托事件,因为它具有奇怪的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM