gpt4 book ai didi

javascript - 在动态元素上设置背景图像

转载 作者:行者123 更新时间:2023-11-28 05:41:46 25 4
gpt4 key购买 nike

我试图在动态创建的元素上设置背景图像,但它似乎不起作用。它应该采用我放入数组中的对象的“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>

当我检查该元素时,它似乎应该可以工作?我迷茫了...

https://jsfiddle.net/qmr32463/

最佳答案

"background-image" 是无效的 jQuery 方法。另一方面, .css() 是有效的,所以

而不是

        'background-image' : 'url(\'' + sponsorArray[i].img + '\')'

用途:

        css : {
backgroundImage: 'url(\'' + sponsorArray[i].img + '\')'
}

https://jsfiddle.net/qmr32463/1/

关于javascript - 在动态元素上设置背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com