繁体   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