如何在 Javascript 中设置对象属性的样式?我得到"Uncaught TypeError: Cannot set property 'fontWeight' of undefined"



这是我的代码,我要做的是访问"属性,并将其样式设置为粗体。一切正常,除了对对象属性进行样式化,这给了我错误"Uncaught TypeError: Cannot set property 'fontWeight' of undefined",即使对象和它的属性存在。

var productes = [
mobil = {
nom: "Galaxy A51",
preu: "300",
img: "../media/mobil.jpg"
},
portatil = {
nom: "Portatil Gaming",
preu: "600",
img: "../media/laptop.jpg"
},

pc = {
nom: "PC Gaming Ultra",
preu: "600",
img: "../media/pc.jpg"
},
cpu = {
nom: "CPU TURBO-X",
preu: "200",
img: "../media/cpu.jpg"
},
cadira = {
nom: "Cadira Gaming Xtreme",
preu: "399",
img: "../media/chair.jpg"
},
ratoli = {
nom: "Ratoli Gaming",
preu: "99",
img: "../media/mouse.jpg"
},
bitcoin = {
nom: "Bitcoin",
preu: "40 000",
img: "../media/bitcoin.jpg"
},
monitor = {
nom: "Pantalla Gaming 1Hz",
preu: "400",
img: "../media/monitor.jpg"
},
web = {
nom: "Aquest lloc web",
preu: "1 000 000",
img: "../media/web.jpg"
}
];
for(var i = 0; i < productes.length; i++) {     //despres aixo anira atraves del array
//i les ficara totes en divs a la pagina
var div = document.createElement("div");
var objNom = productes[i].nom;
var objPreu = productes[i].preu + "&euro;";
var image = document.createElement("img");
//alguns estils i tal
image.src = productes[i].img;
div.style.cssText = "background-color: purple; width: 33%; padding: 10px; margin-top: 30px; box-shadow: 3px 3px 15px 5px black;"
image.style.cssText = "width: 100%;";
div.innerHTML = objNom + "<br><br>" + "Preu: " + objPreu;
objNom.style.fontWeight = "bold"; //REMOVE THIS LINE TO SEE THE CODE WORK
//afegint el div al body i el imatge al div
document.body.appendChild(div);
div.appendChild(image);
};
<body>
</body>

让我在尝试解决你的问题的同时使你的代码现代化。

Object.values(productes).forEach(producte => {
const {nom, preu, img} = producte
let element = `
<div class="producte">
<span><strong>${nom}</strong>: ${preu} &euro;</span>
<img src="${img}" />
</div>`;
document.body.insertAdjacentHTML('beforeend', element);
})
// If you need "mobile", "monitor", "web" etc, replace the first line of script with the code down below, and remove ")" at the end.
// for (const [key, producte] of Object.entries(productes)) {
.producte {
background-color: purple;
width: 33%;
padding: 10px;
margin-top: 30px;
box-shadow: 3px 3px 15px 5px black;
}
.producte img {
width: 100%;
}

我没有注意到你的HTML结果,但是如果你读了我的答案,你就可以看到它是如何产生一个HTML字符串的。

相关内容

最新更新