简体   繁体   中英

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. 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.

 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>

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} &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%;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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