![](/img/trans.png)
[英]Why do I get the error Uncaught TypeError: Cannot set property 'display' of undefined in Javascript?
[英]How do I style an object property in Javascript? I get “Uncaught TypeError: Cannot set property 'fontWeight' of undefined”
所以這是我的代碼,我想做的是訪問 object 的“nom”屬性,並將其設置為粗體。 一切正常,除了設置 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>
讓我在嘗試解決您的問題的同時對您的代碼進行現代化改造。
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%;
}
我沒有注意您的 HTML 結果,但是如果您閱讀我的答案,您可以看到它是如何生成 HTML 字符串的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.