2016-12-06 53 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