我有一堆空的圖像,我需要設置src和動態定位。所有圖像都具有相同的類別,但它們具有不同的src,寬度和高度。動態設置所有圖像(具有相同的類)不同的src,寬度和高度
src,width和height的值作爲屬性存儲在與id匹配的對象中。在我的setImage
函數中,我嘗試使用id.width
等來獲得它們,但是它們是未定義的。我該如何解決這個問題?
的jsfiddle這裏:
HTML:
<div class="img-holder">
<img class="imgs" id="img_11" />
</div>
<div class="img-holder">
<img class="imgs" id="img_12" />
</div>
<div class="img-holder">
<img class="imgs" id="img_13" />
</div>
的javascript:
var img_11 = {
src: "http://lorempixel.com/output/animals-q-c-640-480-2.jpg",
width: 60,
height: 60
};
var img_12 = {
src: "http://lorempixel.com/output/sports-q-c-640-480-4.jpg",
width: 50,
height: 50
};
var img_13 = {
src: "http://lorempixel.com/output/people-q-c-640-480-2.jpg",
width: 100,
height: 100
};
function setImage(id) {
jQuery('#'+id).attr('src', id.src);
jQuery('#'+id).css({width: id.width});
jQuery('#'+id).css({height: id.height});
}
jQuery(document).ready(function() {
jQuery('.imgs').each(function() {
setImage(this.id);
});
});
PS。道歉,如果這是不是很好,我歡迎任何改進,因爲我仍然是相當新的JavaScript和jQuery。