2016-12-06 51 views
0

我正在一个JSON文件上运行每个循环,该文件读取与按钮(.region)上的单击事件相对应的对象,然后使用if语句进行调整。每个循环后通过点击事件获取对象值

这样做没有问题,没有click事件,使用它,并试图让对象输出未定义。

我怎样才能做到这一点使用下列内容:

对象:

var data = { 
    "employees": [{ 
      "title": "Jay Rob", 
      "region": "IL", 
      "startDate": "2016-12-06" 
     }, { 
      "title": "John Doe", 
      "region": "UK", 
      startDate ": "2016-12-06" 

     } 
    ] 
} 

JS:

$(document).ready(function() { 
    $(data.employees).each(function() { 
      var date = "2016-12-06"; 
      var reg = "IL"; 

      if (this.startDate == date) { 

       $('#emp-main').append('<div class="emp-box"><h2>' + this.title + '</h2><span>' + this.region + '</span>'); 
       // Works like it should! 
      } 

      $(".region").click(function() { 
        //an if statement here, taking the current object from the loop, comparing it to the variable region and startDate and outputting HTML. Would not work because of the scope. 
        if (data.employees.region == reg && data.employees.starDate == date) { 
         $('#emp-main').append('<div class="emp-box"><h2>' + this.title + '</h2><span>' + this.region + '</span>'); 
         //returns undefined 
        }); 
      }); 

    }); 
}); 
+0

你不应该申请一个'$内的事件处理程序.each'循环,它将多次绑定到相同的元素当您绑定您的点击事件时,this.title不再处于范围之内 – empiric

+0

。创建一个新变量:'var that = this;'然后在你的点击事件中调用它:'that.title'。否则将其绑定到窗口对象。 – Daerik

+0

您应该使用'$ .each()'来遍历数组。 '$(...)。each()'用于循环匹配'$(...)'中选择器的DOM元素。 – Barmar

回答

1

您正在访问data.employees.region这会给你不确定是肯定的, 因为data.employees是数组,你需要先指定你想要访问的索引,使用$.each就会像这样一个一个地发送

$(data.employees).each(function(i, employee) { 
     // then access region 
    employee.region 
}); 

毕竟,你将面对的是越来越上的所有按钮,最后单击对象,所以你需要将范围与IIFE隔离

$(data.employees).each(function(i, employee) { 
     // here scope for $.each 
     // will affect the $.click scope 
     // because they use the same variable 
     // and $.each ends but the scope still accessible by $.click function 
    (function(emp){ 
     $(".region").click(function() { 
     // because the $.click will be called later 
     // can see what $.each scope last value 

     // to avoid clash with the outer scope of .each 
     // passed to function IIFE 
     // and this act as eval the value of the variable directly on 
     // declare it 

      emp.region 


     }); 
    }(employee)); 
}); 
+0

我仍然无法访问employees.region里面的点击功能... – Ozzy

+0

更新'员工'到'员工' –

+0

我想了解逻辑,你要通过data.employees,你传递给每个函数我和员工,为了什么目的?在那之后,你运行IIFE,你传递给它同样的员工变量在顶部和底部,这是什么意思? – Ozzy