2012-02-19 109 views
-1

我想將一些元素存儲到一個數組中,我需要這個元素的位置。如何將元素的順序存儲到數組中

下面的例子顯示了一個簡單的例子,我想存儲(注意,id會隨着每次頁面加載而改變)。

我想存儲其所有的孩子每個箱父類(DIV)的位置

UPDATE:

主要的想法是讓結構(各元素的這樣的位置)到一個數組/字符串,我認爲它叫做序列化。盒的父類是用於排序塊/小部件(盒1,盒2等)類似的例子容器 可以找到這裏http://james.padolsey.com/demo/tut-inettuts-with-cookies/

基本示例

<div id="main-wrapper"> 

     <div class="box-parent"> 
      <div id="box-1"> content here </div> 
      <div id="box-2"> content here </div> 
      <div id="box-3"> content here </div> 
      <div id="box-4"> content here </div> 
      <div id="box-5"> content here </div> 
     </div> 

     <div class="box-parent"> 
      <div id="box-6"> content here </div> 
      <div id="box-7"> content here </div> 
      <div id="box-8"> content here </div> 
      <div id="box-9"> content here </div> 
      <div id="box-10"> content here </div> 
     </div> 

     <div class="box-parent"> 
      <div id="box-11"> content here </div> 
      <div id="box-12"> content here </div> 
      <div id="box-13"> content here </div> 
      <div id="box-14"> content here </div> 
      <div id="box-15"> content here </div> 
     </div> 

    </div>  
+0

我似乎無法理解你的問題 – elclanrs 2012-02-19 21:33:36

+0

你提出的輸出不是一個數組,它是一個對象 - 和一個無效的對象,因爲你不能使用相同的屬性名稱兩次(或者如果您執行第二個屬性將覆蓋第一個屬性),因此您不能在同一個對象中存儲兩個不同的「box-parent」屬性。也許「main-wrapper」應該是一個實際的數組(方括號'[]'),每個元素都是「box-parent」? – nnnnnn 2012-02-19 22:43:28

回答

1

你的結構不能爲: object['box-parent']不能引用2個不同的值。

您可以通過各種方式獲取職位。假設每個.box-parent有5個元素,你可以應用以下計算:

var elem; // given that elem refers to a "box-X", for instance $('#box-4'): 
elem.prevAll().length + elem.parent().prevAll('.box-parent').length*5 

您還可以枚舉.box-parent與外部計數器,並把位置分爲結構:

var i=0; 
$('.box-parent').each(function() { 
    $(this).children().each(function() { 
     // i = the position 
     // ...    

     i++; 
    }); 
}); 
+0

沒有結構是一個可排序的網格,所以div的數量會改變。 – user759235 2012-02-19 21:59:58

+0

所以用其他方法來枚舉它們。 – ori 2012-02-19 22:03:04

0

使用getElementsByTag (),計算沒有「box-parent」類的元素,並將「position」設置爲與「box-parent」類非元素元素的計數相等。

0

所以,如果我理解這個正確的,你有這樣的

<container> 
    <element class="parent"> 
     <!-- Content #1 --> 
    </element> 
    <element class="parent"> 
     <!-- Content #2 --> 
    </element> 
    <element class="parent"> 
     <!-- Content #3 --> 
</container> 

的結構和您定義與內容#1的元素是第一個元素,並將其向下的增加,你想保留這個順序。

我假設jQuery是可以接受的;如果它沒有讓我知道

// Something like this should work 
$("container").children(".parent") 
// [Element, Element, Element] 

Jsfiddle

相關問題