JavaScript 循环遍历 .children() 项并保存到数组
javascript loop through .children() items and save to array
关于这个问题,我找不到任何适合我的解决方案,所以如果重复,请原谅我。
我想遍历所有 .children() 项目,如果其中一些项目满足条件,我想将这些项目保存在一个数组中。这是准确显示我的意思的代码:
var items = [],
allitems = $('.iconImg').children(),
obj;
// console.log(allitems);
$('#next4').on('click', function(e){
e.preventDefault();
for(var i=0; i<allitems.length; i++){
var currItem = $(allitems[i]).attr('id'),
currItemPosLeft = parseInt($('#'+currItem).css('left')),
itemOffset = getOffset('#'+currItem),
items = [],
arrToSend = [];
// console.log(currItem, '=>', currItemPosLeft);
if(currItemPosLeft >= 405){
obj = {
obId: currItem,
obPos: itemOffset
}
items.push(obj);
console.log(items);
}
}
这段代码为我提供了满足条件的对象的数组数量,但我想要的是一个数组来存储这些对象。
我该怎么做?
谢谢
好的,我解决了。我不知道为什么我这么复杂,这超级容易。
因此,代码将是:
var items = [],
allitems = $('.iconImg').children().toArray(),
obj;
// console.log(allitems);
$('#next4').on('click', function(e){
e.preventDefault();
$(allitems).each(function(i){
var currItem = $(allitems[i]).attr('id'),
currItemPosLeft = parseInt($('#'+currItem).css('left')),
itemOffset = getOffset('#'+currItem);
// console.log(currItem, '=>', currItemPosLeft);
obj = {
odId: currItem,
obPos: itemOffset
};
if(currItemPosLeft >= 405){
items.push(obj);
}
})
console.log(items);
})
//end of #next4 click
只是一个做事的演示;
var testData = [{id:1,data:'abc'},{id:2,data:'efg'},{id:3,data:'pqr'},{id:4,data:'xyz'}]
var res = []
testData.forEach(function(o){
if(o.id % 2 == 0) { //your condition..
res.push({nid:o.id, ndata: o.data})
}
});
演示:http://jsfiddle.net/dpst36xe/
相关文章:
- 保存数组javascript
- 保存表中的行's在数组中的tbody,稍后使用它们
- 保存id数组's而不是对象
- JavaScript-保存、存储和更新数组
- Javascript-将类型化数组保存为blob,并作为二进制数据读回
- 使用javascript/jquery从现有数组中创建一个新数组,该数组保存项目存在的次数
- AJAX将JSON数组保存到多个JS变量中
- 我的函数不会返回要保存在数组中的对象
- Javascript数组只保存最近的对象
- 将对象属性保存到数组时出现奇怪的重复
- 将地理编码器的位置保存到数组中
- 如何在排序前保存数组的副本
- 如何使用保存数组名称的变量将对象文本添加到数组
- 使用猫鼬保存数组数据的更干净的代码
- Javascript:保存数组中重复项的索引
- 在重新加载时保存数组值并将其取回
- 如何在parse.com+AngularJS中使用for循环保存数组中的每个对象
- 使用postgresql保存数组进行Sequelize
- 对象,用于保存数组JQuery
- 如何在文件上快速保存数组