即时通讯尝试创建一个函数,通过一组图像循环并获取它的值并将它们添加到对象/数组。如何获取图像的值到一个对象/数组
<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的两次
你可以改变数据结构?如果您使用ID作为键存储图像属性,而不是将它们存储在数组中,那将会更简单一些。仅供参考,'$(“img .holder”)'应该删除空格。 '$(“img.holder”)''this.attr(...)'将失败。 – 2012-06-06 20:11:09
您将具有唯一标识的图像添加到数组中?你如何在数据中获得相同的id多次? – Challe
@Charles:我认为它是来自'pickimage()'的后续调用。但不知道。 – 2012-06-06 20:11:50