簡體   English   中英

使用JQuery遍歷DOM

[英]Iterating over the DOM with JQuery

我正在嘗試遍歷DIV列表以檢查它們是否有子級 ,如果有,則將該DIV的IDchild一起添加到數組中。 保存建築物用於游戲是很重要的,如果有更好的方法可以實現,我願意提出建議。

HTML

<div id="grid" class="grid">
    <div id="t1" class="tile"></div>
    <div id="t2" class="tile">
        <img class="Extractor" title="Extractor" src="images/buildings/Extractor.png">
    </div>
    <div id="t3" class="tile"></div>
    <div id="t4" class="tile"></div>
    <div id="t5" class="tile active"></div>
</div>

JS

function saveGame() {
// Format like: "[['t2','Extractor']['t8','Forge']]"
  saveData.buildings = $('.tile').children().stuff(?);

  localStorage.saveData = JSON.stringify(saveData);
}

小提琴

.map()方法用於構建新的數組。 在這里,我們選擇子圖像,並針對該集合使用map。

.map()回調的返回值成為新Array的成員。 因為jQuery的.map()很奇怪,所以我們需要將返回的Array加倍,因為任何外部Array都會被展平為結果Array。

$('.tile').children("img").map(function(i, el) { 
    return [[el.parentNode.id, el.className]]; 
}).toArray();

最后使用.toArray()的原因是,此版本的jQuery中的.map()實際上返回一個jQuery對象,該對象類似於Array,但不是實際的Array。 因此,我們需要對其進行轉換。

.each遍歷每個區域,然后.each對孩子遍歷所有這些,有可能是一個更快的算法有人如果有也許有人會評論。

saveData.buildings = "[['t2','Extractor']['t8','Forge']]"; 
$('.tile').each(function(){
   var parent = $(this); 
   parent.children().each(function(){
      saveData.buildings.push([parent.id,$(this).attr("class")]); 
   });
});
saveData.resources = 'resources';

我還沒有測試過,但是這種邏輯的東西應該可以正常工作:

results = [];

// iterate over every element with class 'tile'
$('.tile').each(function() {

  var $$ = $(this);

  // does this instance of class tile have a child?
  if ($$.children().length > 0) {

     // store data
     var parent = $$.attr('id');
     var child  = $$.children().first().attr('class');
     results.append([parent, child]);

  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM