I am trying to to set a specific background for several buttons that I have grabbing an image from a json file. I am trying to apply the css "background" property to it to accomplish this through javascript, but am unsure how to do this. I tested out the current code that I have with simply the color "red", and this works just fine but when i try to pull it from a json file, there are no results. Any help on what I might do to approach this? here is my code:
const t = "js/test.json"
fetch(t)
.then(function (response) {
return response.json();
})
.then(function (jsonObject) {
var color = jsonObject['color'];
for (var i = 0; i < color.length; i++) {
var buttonColor = i;
if (buttonColor == 0 ) {
document.querySelector(".btn").style.background= color[0].image;
}
}
});
and the JSON file I am pulling the image from:
{
"color":[
{
"name": "red",
"image": "colors/red.png",
"small-image":"colors/red-small.png"
},
{
"name": "blue",
"image": "colors/blue.png",
"small-image":"colors/blue-small.png"
},
{
"name": "yellow",
"image": "colors/yellow.png",
"small-image":"colors/yellow-small.png"
},
{
"name": "green",
"image": "colors/green.png",
"small-image":"colors/green-small.png"
}
]
}
The line I mostly need help with is on line 11, where
document.querySelector(".btn").style.background= color[0].image;
is found.
question from:
https://stackoverflow.com/questions/65850585/how-to-set-a-background-to-an-element-from-a-json-file 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…