我试图创建一个函数,它循环遍历一组图像并获取它的值并将它们添加到对象/数组中。
<div id="col1">
<img id="layer_a" src="imga.jpg" height="320" width="400" class="holder">
<img id="layer_b" src="imgb.jpg" height="320" width="400" class="holder">
<img id="layer_c" src="imgc.jpg" height="320" width="400" class="holder">
<img id="layer_d" src="imgd.jpg" height="320" width="400" class="last">
</div>
<div id="col2">
<img id="layer_e" src="imge.jpg" height="320" width="400" class="holder">
<img id="layer_f" src="imgf.jpg" height="320" width="400" class="last">
</div>
剧本:
var data = {};
function pickimage() {
$("img .holder").each(function() {
var idset = this.attr('id');
var srcset = this.attr('src');
var heightset = this.attr('height');
var widthset = this.attr('width');
var newSet = {
'id': idset,
'src': srcset,
'width': widthset,
'height': heightset
};
data.images.push(newSet);
for (var i = 0; i < data.images.length; ++i) {
if (data.images[i].id == id) return i;
}
});
}
pickimage();
我希望数据看起来像这样:
var data = {
"images": [{
"id": "layer_a",
"src": "imga.jpg",
"width": "400",
"height": "320"}]
};
依此类推,没有两次获得相同的ID