我正在尝试在动态创建的元素上设置背景图像,但它似乎不起作用。它应该采用我放入数组的对象的“img”属性,然后将其用于背景图像url。
使用Javascript:
var sponsorArray = new Array();
//Sponsor Constructor Function
function Sponsor(name, img, tier, url, description) {
this.name = name;
this.img = img;
this.tier = tier;
this.url = url;
this.description = description;
//A counter for the number of sponsors
Sponsor.num = (Sponsor.num || 0) + 1;
//Insert this object into the sponsors array
sponsorArray.push(this);
};
var sponsor0 = new Sponsor(
'test sponsor',
'./images/sponsors/test.png',
'Platinum',
'test.com',
'blah blah blah'
);
var initSponsors = function() {
for (var i = 0; i < sponsorArray.length; i++) {
var sponsor_image = $('<li>', {
'class': 'sponsor-logo',
'id': 'sponsor' + i,
'background-image': 'url(\'' + sponsorArray[i].img + '\')'
});
$('#logo-sponsors').append(sponsor_image);
}
};
initSponsors();
HTML:
<ul id="logo-sponsors">
</ul>
当我检查元素时,看起来应该有效吗?我不知所措......
答案 0 :(得分:0)
"background-image"
是一种无效的jQuery方法。另一方面.css()
有效,所以
而不是
'background-image' : 'url(\'' + sponsorArray[i].img + '\')'
使用:
css : {
backgroundImage: 'url(\'' + sponsorArray[i].img + '\')'
}