2014-06-17 46 views
1

我有一堆空的圖像,我需要設置src和動態定位。所有圖像都具有相同的類別,但它們具有不同的src,寬度和高度。動態設置所有圖像(具有相同的類)不同的src,寬度和高度

src,width和height的值作爲屬性存儲在與id匹配的對象中。在我的setImage函數中,我嘗試使用id.width等來獲得它們,但是它們是未定義的。我該如何解決這個問題?

的jsfiddle這裏:

http://jsfiddle.net/nNh2n/2/

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。

回答

1

爲什麼不乾脆把它們放在一個對象,然後訪問屬性:

var obj = { 
    'img_11': { 
     src: "http://lorempixel.com/output/animals-q-c-640-480-2.jpg", 
     width: 60, 
     height: 60 
    }, 
     'img_12': { 
     src: "http://lorempixel.com/output/sports-q-c-640-480-4.jpg", 
     width: 50, 
     height: 50 
    }, 
     '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', obj[id].src); 
    jQuery('#' + id).css({ 
      width: obj[id].width, 
      height: obj[id].height 
     }); 
} 

jQuery(document).ready(function() { 
    jQuery('.imgs').each(function() { 
     setImage(this.id); 
    }); 
}); 

演示:http://jsfiddle.net/lotusgodkk/nNh2n/3/

1

我會使用一個對象數組,使圖像id對象的另一個屬性。看到一個working fiddle here

var images = [{ 
    id: 'img_11', 
    src: "http://lorempixel.com/output/animals-q-c-640-480-2.jpg", 
    width: 60, 
    height: 60 
}, { 
    id: 'img_12', 
    src: "http://lorempixel.com/output/sports-q-c-640-480-4.jpg", 
    width: 50, 
    height: 50 
}, { 
    id: 'img_13', 
    src: "http://lorempixel.com/output/people-q-c-640-480-2.jpg", 
    width: 100, 
    height: 100 
}]; 

function setImage(image) { 
    jQuery('#'+image.id).attr('src', image.src); 
    jQuery('#'+image.id).css({width: image.width}); 
    jQuery('#'+image.id).css({height: image.height}); 
} 

jQuery(document).ready(function() { 
    for (var i = 0; i < images.length; i++) { 
     setImage(images[i]); 
    } 
}); 
相關問題