2013-01-15 33 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