我已經設法在想要的位置創建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