简体   繁体   English

在JavaScript对象数组中存储CSS属性

[英]Storing css property inside JavaScript object array

I am trying to store and retrieve the id and background colors of the clicked div elements of the class "square". 我正在尝试存储和检索“正方形”类单击的div元素的ID和背景色。 However, when I try to print the stored value, I am getting 'undefined'. 但是,当我尝试打印存储的值时,出现“未定义”的情况。

var colorObject = [
    {
        objColor:null,
        squareId:null
    },
    {
        objColor:null,
        squareId:null
    }
];
document.getElementById("container").addEventListener("click", function(e) {
// Event delegation used to find the clicks on the squares within the "Container"
    // e.target was the clicked element
    if (e.target && e.target.matches("div.square")) {
        console.log("Square element clicked!");

        colorObject[0].objColor=this.style.backgroundColor;
        console.log(this.objColor);
        colorObject[0].squareId=this.getAttribute('id');
        console.log(this.squareId);
   }
});

If you re-examine what your are passing to console.log , you'll notice that it is this.objColor and this.squareId , which are not the values which you just set. 如果您重新检查传递给console.log ,您会注意到它是this.objColorthis.squareId ,它们不是您刚刚设置的值。 Change these to colorObject[0].objColor and colorObject[0].squareId and you would have better luck I think: 将它们更改为colorObject[0].objColorcolorObject[0].squareId ,我认为您会更好。

colorObject[0].objColor=this.style.backgroundColor;
console.log(colorObject[0].objColor);
colorObject[0].squareId=this.getAttribute('id');
console.log(colorObject[0].squareId);

On a side note, it's a good practice to be consistent with your spacing, and careful when uploading to SO because sometimes it gets messed up a little. 附带说明一下,与您的间隔保持一致是一个好习惯,并且在上传到SO时要小心,因为有时会有些混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM