[英]How do I style an object property in Javascript? I get “Uncaught TypeError: Cannot set property 'fontWeight' of undefined”
So here's my code, and what I am trying to do is access "nom" property of an object, and styling it bold.所以这是我的代码,我想做的是访问 object 的“nom”属性,并将其设置为粗体。 Everything works, except for styling the object property, which gives me the error "Uncaught TypeError: Cannot set property 'fontWeight' of undefined", even though the object and its property exist.
一切正常,除了设置 object 属性的样式,这给了我错误“Uncaught TypeError: Cannot set property 'fontWeight' of undefined”,即使 object 及其属性存在。
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 + "€"; 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>
Let me modernize your code while trying to solve your problem.让我在尝试解决您的问题的同时对您的代码进行现代化改造。
Object.values(productes).forEach(producte => {
const {nom, preu, img} = producte
let element = `
<div class="producte">
<span><strong>${nom}</strong>: ${preu} €</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%;
}
I didn't pay attention to your HTML outcome, but if you read my answer, you can see how it can be produced an HTML string.我没有注意您的 HTML 结果,但是如果您阅读我的答案,您可以看到它是如何生成 HTML 字符串的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.