Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

javascript - How to set a background to an element from a JSON file

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can set the backgroundImage property instead

 document.querySelector(".btn").style.backgroundImage = `url(${color[0].image})`;

Note: the path to your file must be correct so now it will look if there is a directory colors and if inside this directory is a png named red.png.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...