我正在尝试存储和检索类“方形”的已单击 div 元素的 ID 和背景颜色。但是,当我尝试打印存储的值时,我得到“未定义”。
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);
}
});
最佳答案
如果您重新检查传递给 console.log
的内容,您会注意到它是 this.objColor
和 this.squareId
,这不是您刚刚设置的值。将它们更改为 colorObject[0].objColor
和 colorObject[0].squareId
我认为你会更幸运:
colorObject[0].objColor=this.style.backgroundColor;
console.log(colorObject[0].objColor);
colorObject[0].squareId=this.getAttribute('id');
console.log(colorObject[0].squareId);
附带说明一下,保持间距一致是一个好习惯,上传到 SO 时要小心,因为有时它会有点困惑。
关于javascript - 在 JavaScript 对象数组中存储 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49215844/