2013-01-15 31 views
0

我试图学习更好地构建我的代码,并且在遵循一些教程之后开始使用下面的模式。

我已经用这种方式构建了许多常见UI小部件,但我已经击中了我的第一面墙,下面的.each()循环似乎实际上并不是循环遍历每个项目正在应用所需的操作,就好像它在一次迭代中对所有项目执行操作一样。

我读了一些关于$ .each和objects的内容,但我不确定$ .each,甚至是否是我应该去的方向。

jQuery(document).ready(function($) { 

var tabs = { 

    trig : $('nav.tab-triggers'), 
    content : $('section.tabs-content'), 

    init : function() { 
     tabs.address([tabs.trig]); 
     tabs.address([tabs.content]); 
    }, 

    address : function(item) { 
     //for every instance of the item 

     $(item).each(function() { 
      var i = 1; 
      $(this).addClass('tabs-' + i); 

      // for ever child element in this instance of the item 
      $(this).children().each(function() { 
       var count = 1; 
       if ($(this).parent().is('nav')) { 
        $(this).attr('href', '#tab-' + count); 
       } else { 
        $(this).attr('id', 'tab-' + count); 
       } 

       count++; 

      }); 

      i++; 
     }); 
    }, 

    display : function() { 
     //show hide stuff here. 
    } 


} 

tabs.init(); 

}); 
+0

我注意到你用你自己的柜台,就可以使用 $(项目)。每个(函数(指数){ }); 不理解你的问题的其余部分 –

+0

嘿感谢您的输入,如果我可以进一步解释,基本上所有的孩子获得相同的href(在导航的情况下)或身份证,而不是递增的 - 好像它是处理所有与每个元素相对的匹配元素,因为它应该循环。 – pushplaybang

+0

所以你得到所有元素相同的ID或HREF? –

回答

0

因此,经过多次试验和错误,我终于得到它的工作。

基本上,据我所知,我试图遍历一个嵌套的objet,所以.each需要用$ .each方法替换,它的工作方式稍有不同。

address : function(obj) { 
     // for each obj 
     $.each(obj, function(index,value) { 
      //for each instance of the trigger/content item in the obj 
      $.each(obj[index], function(index2,value2) { 
       //add an incrementing class for each matched element 
       $(value2).addClass('tabs-' + index2); 
       // get the children of each matched element 
       var kids = $(value2).children(); 
       // loop through each of the children 
       $.each(kids, function(index3, value3) { 
        // if its parent is a nav element 
        if ($(value3).parent().is('nav')) { 
         // add href 
         $(value3).attr('href', '#tab-' + index3); 
        } else { 
         // add matching ids 
         $(value3).attr('id', 'tab-' + index3); 
        } 


       }); // end loop through children elements 
      }); // end loop through parent elements 
     }); // iteration of passed obj 
    }, // end address method 

这就是新的方法 - 这是有效的。有一个更好的方法吗 ?

+0

我假设你有一些html去与此,你可以张贴吗?这是很难理解的。 –

+0

@MatthewGrima - 确定 - 这里是[jsfiddle](http://jsfiddle.net/QUbnv/1/) – pushplaybang

+0

的链接检查结果选项卡中的源代码或查看已添加的classes/ids/hrefs方法。 – pushplaybang