0

我试图创建一个函数,它循环遍历一组图像并获取它的值并将它们添加到对象/数组中。

<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

4

3 回答 3

1

小提琴

当我在小提琴上工作时,你得到了几个类似的答案。检查最适合您的那一款

JS

var data = {
    'images': Array()
}

function pickimage() {
$("#imagecontainer").find('img').each(function() {
    var img= $(this)
    var idset = img.attr('id');
    var srcset = img.attr('src');
    var heightset = img.attr('height');
    var widthset = img.attr('width');
    var newSet = {
      'id': idset,
      'src': srcset,
      'width': widthset,
      'height': heightset
    };
    data.images.push(newSet);

});

}

pickimage();
alert(JSON.stringify(data))
于 2012-06-06T20:35:45.477 回答
1

您必须将您的 JS 修改为

var data = {
    images: []
};

function pickimage() {
    $("img.holder").each(function() {
        var _self = $(this);
        data.images.push({
            'id': _self.attr('id'),
            'src': _self.attr('src'),
            'width': _self.attr('width'),
            'height': _self.attr('height')
        });
    });
}

pickimage();

for (var i = 0, len=data.images.length; i < len; i++) {
    console.log(data.images[i]);
}

http://jsfiddle.net/LDFrp/

于 2012-06-06T20:26:51.130 回答
1

我认为@am not i am 是正确的,有后续电话。如果您需要打这些电话,我有一个简单的 (jsFiddle)[http://jsfiddle.net/CypAA/] 可以解决这个问题。

var data = [];
var ids = {};

function pickImage() {
    $('img.holder').each(function() {
        if (ids[this.id]) return;
        ids[this.id] = 1;

        data.push({
            id: this.id,
            src: this.src,
            width: this.width,
            height: this.height
        });
    });
}

pickImage();
pickImage();
pickImage();

console.log(data);​
于 2012-06-06T20:19:05.883 回答