每次循环后通过单击事件获取对象值

时间:2016-12-06 21:03:44

标签: javascript jquery

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

如果没有click事件,使用它并试图让对象输出undefined就没有问题。

如何使用以下方法实现此目的:

对象:

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
                    });
            });

    });
});

1 个答案:

答案 0 :(得分: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));
 });