Is there a way to style individual array elements in js

微笑、不失礼 提交于 2019-12-25 19:08:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!