问题
I am currently working on a memory game where I have a game board populated with divs created through js
. I'm trying to add images to my array values.
Here is my array:
var memory_array = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H'];
I would like to attach an image to each pair to make my project more interesting. I am currently trying
memory_array[0].style.background-image
and it is breaking my project. Any help would be greatly appreciated.
回答1:
It's .backgroundImage
, but your array consists of char values, they don't have the property style
. For calling .style
, you have to get the DOM
element, f.e. with document.getElementById
or document.getElementsByClassName
. I would recommend to give them class names (.className
) and setting the images in css instead of using .style.backgroundImage
directly.
回答2:
The reason it is not working is because your array elements are strings and not objects. One easy solution would be to make your array like this:
var memory_array = [{name:'A'}, {name:'B'}, ...];
Now, after calling memory_array[0].style-background-image:"SomeImage"
; Your first element would become:
{name: 'A',
style-background-image: "SomeImage"
}
Note that this does not change any style directly. When building DOM elements you will have to call the property style.backgroundImage
and apply it to each element
来源:https://stackoverflow.com/questions/32176870/is-there-a-way-to-style-individual-array-elements-in-js