我正在一個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
});
});
});
});
你不應該申請一個'$內的事件處理程序.each'循環,它將多次綁定到相同的元素當您綁定您的點擊事件時,this.title不再處於範圍之內 – empiric
。創建一個新變量:'var that = this;'然後在你的點擊事件中調用它:'that.title'。否則將其綁定到窗口對象。 – Daerik
您應該使用'$ .each()'來遍歷數組。 '$(...)。each()'用於循環匹配'$(...)'中選擇器的DOM元素。 – Barmar