![](/img/trans.png)
[英]Iterating over jQuery DOM elements in coffeescript: $(@). shortcut
[英]Iterating over the DOM with JQuery
我正在尝试遍历DIV列表以检查它们是否有子级 ,如果有,则将该DIV的ID与child的类一起添加到数组中。 保存建筑物用于游戏是很重要的,如果有更好的方法可以实现,我愿意提出建议。
<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>
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.