我正在一个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