2016-05-13 134 views
1

我想不必编写额外的函数来填充areas_of_interest变量,我可以这样做吗?返回一个函数内的对象

function prepareResults() { 

    var area_of_interest = $('.checkboxes-wr').find("li"); 

    if (area_of_interest.length) { 

     $.each(area_of_interest, function(x){ 

      results.items[x] = { 
       'id' : $(this).attr("id"), 
       'title' : $(this).find("h6").text().trim(), 
       'areas_of_interest' : function() { 
        return {'test' : 'test'}; 
       }, 
       'potential_treatments' : {} 
      } 


     }); 

    } 

} 
+1

这取决于你需要做什么功能。在这种情况下,您可以简单地将函数存储在'$ .each'之外的变量中(或者甚至在'populateResults'之外),并在结果对象中引用该变量。但是,如果您需要在函数内部使用特定的变量值(即a * closure *),那么您需要在适当的位置声明它的函数。 –

+0

我需要访问在循环过程中定义的“x”变量,不知道该怎么办 – user990717

+0

我需要构建一个对象,该对象将绑定到感兴趣的区域,该对象将具有在其循环的li下的所有复选框 – user990717

回答

0

这工作:

功能prepareResults(){

var area_of_interest = $('.checkboxes-wr').find("li"); 

    if (area_of_interest.length) { 

     $.each(area_of_interest, function(x){ 

      var interests = function(x) { 
       return {'test' : x} 
      } 

      results.items[x] = { 
       'id' : $(this).attr("id"), 
       'title' : $(this).find("h6").text().trim(), 
       'areas_of_interest' : interests(x), 
       'potential_treatments' : {} 
      } 


     }); 

    } 

} 

感谢大家谁在上面的评论帮助。