2014-01-06 155 views
1

我有以下的html:jQuery的添加li元素數組

 <ul id="note-item-lists" class="list-group list-group-sp"> 
    <li id="1" class="list-group-item"> 
     <div id="note-4" class="view"> 
      <button class="destroy close hover-action">×</button> 
      <div class="note-name"> 
       <strong id="new_note_title"> New note </strong> 
      </div> 
     </div> 
    </li> 
    <li id="2" class="list-group-item"> 
     <div id="note-4" class="view"> 
      <button class="destroy close hover-action">×</button> 
      <div class="note-name"> 
       <strong id="new_note_title"> Old note </strong> 
      </div> 
     </div> 
    </li> 
    </ul> 

現在我希望這兩個<li>的存儲到一個數組。

爲此我已經創建了下面的JavaScript代碼:

var notes = new Array(); 

$('.list-group-item').each(function(){ 
    notes[$(this).id] = $(this); 
}); 

然而,當我調試我得到一個空array什麼想法?

+0

也許你只是想:'var $ lis = $('。list-group-item')'。這比保存DOM元素的數組好,它是一個jQuery集合。你想用這些ID做什麼?他們爲什麼對你的陣列很重要? – elclanrs

+0

@elclanrs以上是長php生成列表的示例:)真正的應用程序將有數百個項目,其中id與數據庫引用的id相匹配 –

+0

爲什麼不能將您的DOM保留在jQuery集合中。當你需要獲取一些元素並檢索它們的id時,過濾集合,映射id,然後映射'.toArray'。儘可能地保持你的jQuery集合,這是我的建議。 – elclanrs

回答

2

你快到了。 id是DOM節點的屬性,而不是jQuery對象的屬性,所以您應該使用this.id而不是$(this).id

var notes = []; 
$('.list-group-item').each(function() { 
    notes[this.id] = $(this); 
}); 

請記住,你的第一個li元素具有1id,但JavaScript數組是零索引,所以notes(即notes[0])的第一個元素將是undefined。我建議只是將它們推到數組中出現的順序:

var notes = []; 
$('.list-group-item').each(function() { 
    notes.push($(this)); 
}); 
+0

也注意不是一個數組它應該是一個對象 –

+0

@Peter感謝您的幫助!該ID是以後搜索所需的。然而,我在想,JavaScript沒有什麼比較hashmap?可以? –

+0

它在Javascript中被稱爲對象。你可以使用'var notes = {}'來代替'var notes = []''來像使用哈希映射一樣使用它。 (注意,'[]'和'{}'比'new Array()'和'new Object()'更快更短。) –

0

如果您在Chrome控制檯檢查,你應該把它聲明爲一個對象,你正在使用它作爲一個對象。 Chrome是怪異與控制檯陣列(當然,實際上他們做的是正確的,如JavaScript數組基本上都是對象,並且有沒有關聯數組本身):

x = new Array() 
//[] 
x['a'] = 1 
//1 
x 
//[] 

但是:

x = {} 
//Object {} 
x['a'] = 1 
//1 
x 
//Object {a: 1}