Javascript jquery:构造的数据未定义

Javascript jquery:构造的数据未定义,javascript,jquery,Javascript,Jquery,我花了很多时间想弄明白但什么也没找到 function constructAgenciesData() { $.ajax({ url: "getAgenciesAndGlobalJson.do", dataType: "json", success: function(data){ $.each(data, function (index, row) {

我花了很多时间想弄明白但什么也没找到

    function constructAgenciesData() {       
        $.ajax({
           url: "getAgenciesAndGlobalJson.do",
               dataType: "json",
           success: function(data){
            $.each(data, function (index, row) { 
                  // console.log("data : "+ JSON.stringify(data));
                   $("#"+row.id).data("assignedAgencies", row.assignedAgencies).data("restOfAgencies", row.restOfAgencies).data("global", row.global).data("globalID", row.globalID);      
                  });    
                }        
         });  

   } 
   constructAgenciesData();
   $(function($){ 

      $(".globalswitch").each(function () {
         var idRow = $(this).parents('tr')[0].id;
         alert(idRow);
         console.log($('#'+idRow).data("global"));// <-- UNDEFINED
        $(this).switchButton({
            checked: row.data("global") 
        });
    });

     $(document).on('click','button.btn', function () {     
        var idRow = $(this).parents('tr')[0].id;  
        var title = $(this).parents('td:first').siblings(':eq(1)').text();
        title = "Rule Name :  " + title;
        $("#divPopUp").data('param_1', idRow);
        $("#divPopUp").data('opener', this).dialog("option", "title", title).dialog("open");
        console.log($('#'+idRow).data("global"));// <-- WORKING
        var old_array = $('#'+idRow).data("restOfAgencies"); 
        var new_array = $('#'+idRow).data("assignedAgencies"); 
        addCheckbox(diff(old_array,new_array));

    });


    });
未在
中定义。每个
函数中都未定义


但是它在click函数中工作。

您的
$。ajax
调用是异步的。这意味着它在运行其余的
Javascript
时触发请求

constructAgenciesData()
中的
success
函数可能在IIFE
$(函数($){
之前未完成

因此,无法保证在您尝试在
$(“.globalswitch”).每个
循环中访问
.data('global')
时,会设置
.data('global')

此问题的解决方案是将
$(“.globalswitch”)。每个
循环包装在一个函数
globalSwitchLoop()
中,并在
$.ajax
调用成功时触发该循环


另外,看看。

但是为什么我们可以读取.data('global')在第二个函数中单击?因为
success
函数完成了。这只是应用了一个侦听器,但实际上并没有执行单击回调。我很确定,如果您能够很快单击
按钮。btn
,您将得到相同的
未定义的
错误。我刚刚创建了这个JSFIDLE,不知道是什么为什么它是在JSFIDLE中编写的,而不是在我的代码中。你应用了我的建议吗?Phil,你是最好的,我做了globalSwitchLoop(),现在工作很好。
console.log($('#'+idRow).data("global"));