2010-10-28 68 views
3

我正在研究一個將每個子元素都推送到全局數組(稍後在我的腳本中進行處理)的腳本,但由於某種原因,它實際上並未將元素推入數組。使用jQuery將子元素推入全局數組

代碼:

var childElements=new Array();  
function getChildren(elem){ 
      $(elem).children().each(function(index, value){ 
       childElements[index] = $(this); 
      }); 
     } 

我做錯什麼了嗎?

回答

3

由於jQuery對象是一個類似於數組的對象,因此我可能只是使用它而不是創建一個單獨包裝的對象數組。

var childElements=$(elem).children(); 

如果你打算加入更多的元素,你可以隨時.push().add()元素。這也將確保你沒有重複。

var childElements= $();  
function getChildren(elem){ 
    childElements = childElements.add($(elem).children()); 
} 
+0

哇,這非常有幫助!我一直在尋找一種方法來清理我的代碼。謝謝! – dennismonsewicz 2010-10-28 19:52:02

2
$.each($(elem).children(), function(index, value){ 
       childElements[index] = $(this); 
      }); 

編輯:帕特里克是使一個有效點。如果你只需要一個子對象數組,那麼簡單的var childElements = $('selector').children();就足夠了。除非您希望該數組的值包含(組合)來自子元素的特定屬性,否則不需要該函數。

+0

甜!謝謝!我在我的工作代碼中添加了 – dennismonsewicz 2010-10-28 19:15:38

+0

@dennismonsewicz - 我有點困惑。這在功能上等同於您的原始代碼。 – user113716 2010-10-28 19:30:42

+0

@patrick - 你會如何簡單地使用我的代碼?不得不循環遍歷每個數組是我能想出辦法的唯一方法 – dennismonsewicz 2010-10-28 19:38:15