我已经设法在想要的位置创建div,但是当添加背景图片时,我无法做到。第一次尝试这个,这样裸露在我身上。创建div并添加背景图片
我创建div的循环,然后我试图在相同的循环中添加一个背景图像。我不知道这是问题还是别的,如果是这样的话,请帮我做另一个。
我试过做类似itemContainer[i]
但我无法让它工作。
更新:原因是我的数组是空的,不知道我在做什么错误。
var cicon = [];
$.ajax({
url: '/json/test.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.test).each(function(index, value) {
cicon.push(value.Icon);
/*console.log(value.Icon) works here,
so there's something wrong when I'm adding it to the array.*/
});
}
});
for (var i = 0, n = 10; i < n; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.innerHTML = "item" + i;
itemContainer.style.width = "86px";
itemContainer.style.height = "86px";
itemContainer.style.margin = "5px";
itemContainer.style.border = "2px solid black";
itemContainer.style.borderRadius = "10px";
itemContainer.style.float = "left";
var iconstring = 'url(\'' + cicon[i] + '\')';
itemContainer.style.backgroundSize = "100% 100%";
itemContainer.style.backgroundImage = iconstring;
document.getElementById('page').appendChild(itemContainer);
}
如果你想知道,这个数组包含的URL看起来像这样:https://steamcdn-a.akamaihd.net/apps/440/icons/earbuds.f6dc85683202f2530ae8728880f4a47d4b013ea8.png
@Jecoms那条斜线是逃避“。我会使用'“url('”+ cicon [i] +“')”'我自己,但这是有效的 – DelightedD0D
@ DelightedD0D当然可以。心智编译器处于插值模式,并修剪了外部字符串的单引号。 – Jecoms