[英]Get object value through a click event after each loop
我在JSON文件上運行每個循環,該循環獲取與button(.region)上的click事件相對應的對象,然后使用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
});
});
});
});
您正在訪問data.employees.region
這肯定會給您未定義的信息,因為data.employees
是數組,您需要先指定要訪問的索引,使用$.each
會像這樣$.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));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.