2012-06-06 32 views
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的两次

+0

你可以改变数据结构?如果您使用ID作为键存储图像属性,而不是将它们存储在数组中,那将会更简单一些。仅供参考,'$(“img .holder”)'应该删除空格。 '$(“img.holder”)''this.attr(...)'将失败。 – 2012-06-06 20:11:09

+0

您将具有唯一标识的图像添加到数组中?你如何在数据中获得相同的id多次? – Challe

+0

@Charles:我认为它是来自'pickimage()'的后续调用。但不知道。 – 2012-06-06 20:11:50

回答

1

我觉得@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);​ 
+0

谢谢!解决了这个问题 –

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/

1

fiddle

当我工作的小提琴,你有几个类似的答案。检查最适合你的一个

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)) 
相关问题