簡體   English   中英

如何在 javaScript 文件中使用 html 打印/渲染嵌套對象屬性

[英]How to print/render nested objects properties using html in javaScript file

我正在搜索嵌套對象。 我想渲染對象屬性,但每次我必須進入像 mobiles.apple.iphone12.properties 這樣的對象。 如果我願意,我有多個手機在對象中,這將是非常冗長的代碼。 我只想以更短的方式打印。 查看下面的 JavaScript 代碼。

 let searchBtn = document.getElementById('search-btn') let mobiles = { apple: { iphone13: { model: 'iphone 13', color: 'black', price: 1000, camera: 20, battery: 500, }, iphone12: { model: 'iphone 12', color: 'red', price: 800, camera: 15, battery: 400, src: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRhdp92UKK3NxwNfcIBlyZX8g26kEYBG3WNoQ&usqp=CAU" } }, samsung: { s10: { model: 'Samsung S10', color: 'black', price: 500, camera: 10, battery: 600, }, a10: { model: 'Samsung A10 ', color: 'blue', price: 300, camera: 20, battery: 150, } }, moto: { motoz: { model: 'Moto Z', color: 'black', price: 500, camera: 10, battery: 300, }, motoe4: { model: 'Moto E4', color: 'black', price: 200, camera: 10, battery: 300, } }, techno: { camon18: { model: 'Camon 18', color: 'golden', price: 5000, camera: 10, battery: 300, }, spark7: { model: 'Spark 7', color: 'sky blue', price: 2000, camera: 10, battery: 300, } } } searchBtn.addEventListener('click', function () { let brandName = document.getElementById('brand-name').value let modelName = document.getElementById('model-name').value if (mobiles[brandName] !== undefined) { if (mobiles[brandName][modelName] !== undefined) { console.log(mobiles[brandName][modelName]) } else { console.log('This model is not available') } } else if (brandName == '' || modelName == '') { console.log('Brand name OR Model name is empty') } else { console.log('This model is not available') } }) let card = `<div class="card"> <img src="${mobiles.apple.iphone12.src}" style="width:100%"> <h1> ${mobiles.apple.iphone12.model} </h1> <p class="price"> Rs: ${mobiles.apple.iphone12.price}</p> <p> Color: ${mobiles.apple.iphone12.color} </p> <p> Battery: ${mobiles.apple.iphone12.battery} </p> <p><button>Add to Cart</button></p> </div>` document.getElementById("container").innerHTML += card
 #container { display: flex; justify-content: space-around; flex-wrap: wrap; } .card { box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); width: 300px; margin: 50px; text-align: center; font-family: arial; } img { margin-top: 20px; } .price { color: grey; font-size: 22px; } .card button { border: none; padding: 12px; color: white; background-color: #000; text-align: center; cursor: pointer; width: 100%; font-size: 18px; } .card button:active { opacity: 0.7; }
 <input type="text" id="brand-name" placeholder="Enter Brand Name"> <input type="text" id="model-name" placeholder="Enter Model Name"> <button id="search-btn">Searh Phone</button> <div id="container"> </div>

因此,據我了解,您正在嘗試創建初始顯示的項目。

您可以有一個通用函數來生成過濾或未過濾的卡片。

const generateCards = (brand = '', model = '') => {
    const fragment = document.createDocumentFragment();
    
    Object.entries(mobiles)
    .filter(([key]) => key.includes(brand))
    .forEach(([, mobile]) => {
        Object.entries(mobile)
        .filter(([key]) => key.includes(model))
        .forEach(([, model])=> {
            const card = document.createElement('div');
            card.classList.add('card');
            card.innerHTML = `${model.src ? ('<img src=' + model.src + '} style="width:100%">') : ''}
                <h1> ${model.model} </h1>
                <p class="price"> Rs: ${model.price}</p>
                <p> Color: ${model.color} </p>
                <p> Battery: ${model.battery} </p>
                <p><button>Add to Cart</button></p>`;
            fragment.appendChild(card)
        })
    })

    document.getElementById("container").innerHTML = fragment;
}

然后您可以最初調用generateCards() ,它將生成所有卡片,並且在品牌和模型的偵聽器上,您只需使用這些值調用它generateCards(brand, model)

在閱讀您的問題時,我假設您希望用戶搜索品牌/型號並獲得設備規格(如果存在)作為輸出。

如果是這樣,您應該做的第一件事是將卡片的創建放入您的事件監聽器定義中,否則您將無法渲染它們中的任何一個。

我在下面的代碼段中做了一些更改; 在這種情況下,您不必提前創建指定型號和品牌的card

 searchBtn.addEventListener('click', function () { let brandName = document.getElementById('brand-name').value; let modelName = document.getElementById('model-name').value; if (!mobiles[brandName] || brandName == '') { console.log('Brand not available'); return; } if (!mobiles[brandName][modelName] || modelName == '') { console.log('Model not available'); return; } console.log(mobiles[brandName][modelName]); // Clear previous search document.getElementById('container').innerHTML = null; document.getElementById('container').innerHTML += getMobileinfoHtmlElement( mobiles[brandName][modelName] ); }); function getMobileinfoHtmlElement(mobile) { return `<div class="card"> <img src="${mobile.src}" style="width:100%"> <h1> ${mobile.model} </h1> <p class="price"> Rs: ${mobile.price}</p> <p> Color: ${mobile.color} </p> <p> Battery: ${mobile.battery} </p> <p><button>Add to Cart</button></p> </div>`; }

如果您要使用嵌套對象,則此代碼有效。 說到最佳實踐,數組應該更好; 他們有預建的方法,比如.filter().find()在這種情況下很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM