简体   繁体   English

Javascript - 将变量和对象打印到 HTML

[英]Javascript - printing out variables & objects to HTML

So I'm trying to create an online shop using HTML and Javascript as an exercise.所以我正在尝试使用 HTML 和 Javascript 创建一个在线商店作为练习。 I'm currently working on a dropdown menu which allows me to select the category of the item I wish to shop for (etc. electronics, clothes) but I'm having trouble getting all these values related to the category to show up.我目前正在使用一个下拉菜单,它允许我选择我想购买的商品类别(例如电子产品、衣服),但我无法显示与该类别相关的所有这些值。

So for example, I have a part of a javascript file below.例如,我在下面有一个 javascript 文件的一部分。 The line div.innerHTML = (electronics.store) lets me print out the electronics store name "Mike's Computers" to the HTML file on my browser but I'm not quite sure how to access all the objects under its inventory. div.innerHTML = (electronics.store)让我将电子商店名称"Mike's Computers"打印到浏览器上的 HTML 文件中,但我不太确定如何访问其库存下的所有对象。 Is there a way to possibly iterate through the whole electronics inventory and print out each of the items and its cost/information below it and such?有没有办法遍历整个电子产品库存并打印出每个项目及其下方的成本/信息等?

If not, how would I go about printing things like the laptop brand name?如果没有,我将如何打印诸如笔记本电脑品牌名称之类的东西? Would it just be div.innerHTML = (electronics.inventory[0].brand) to print out the word "iMac"?是否只是div.innerHTML = (electronics.inventory[0].brand)打印出"iMac"?这个词"iMac"? I'm very confused and would appreciate any help possible.我很困惑,希望得到任何可能的帮助。

Ultimately, I'd want my information to show up on the HTML page like:最终,我希望我的信息显示在 HTML 页面上,例如:

Mike's Computers迈克的电脑

Laptops笔记本电脑

iMac $2000 iMac 2000 美元

Dell $600戴尔 600 美元

Computers电脑

Windows PC $1300视窗电脑 $1300

and so on.等等。

function showOptions(){
    let userPicked = document.getElementById("list").value;
    var div = document.getElementById("div");
    if(userPicked == 'one'){
        div.innerHTML = (electronics.store);
    }else{
        alert("You must select a store.");
    }
}

let electronics = {
    store: "Mike's Computers",
    inventory: {
        "Laptops": {
            0: {
                brand: "iMac",
                cost: 2000
            },
            1: { 
                brand: "Dell",
                cost: 600
            }
        },
        "Computers": {
            2: {
                brand: "Windows PC",
                cost: 1300
            }
        }
    }
};

Here is sample code to add the data.这是添加数据的示例代码。

 let electronics = { store: "Mike's Computers", inventory: { "Laptops": { 0: { brand: "iMac", cost: 2000 }, 1: { brand: "Dell", cost: 600 } }, "Computers": { 2: { brand: "Windows PC", cost: 1300 } } } }; function showOptions(){ let userPicked = document.getElementById("list").value; var div = document.getElementById("div"); if(userPicked == 'one'){ var newContent = (electronics.store); newContent += '<br>'; Object.keys(electronics.inventory).forEach(key => { newContent += '<br>'; newContent += key; newContent += '<br>'; var items = Object.values(electronics.inventory[key]); items.forEach(item => { newContent += `&nbsp; ${item.brand} $${item.cost}`; newContent += '<br>'; }); }); div.innerHTML = newContent; }else{ alert("You must select a store."); } } showOptions();
 <input type="text" id="list" value="one"> <div id="div"> </div>

Step one, take as much presentation out of your JavaScript as possible.第一步,尽可能多地使用 JavaScript 进行演示。 Create the structure using HTML.使用 HTML 创建结构。 Then populate that structure using JavaScript.然后使用 JavaScript 填充该结构。 That way if you want to change the layout, you're changing HTML and CSS and NOT Javascript.这样,如果您想更改布局,您将更改 HTML 和 CSS 而不是 Javascript。 Use the <template> tag to create the structure of the repeating items.使用<template>标签创建重复项的结构。

Step Two, iterate the properties, cloning our template, then add to the DOM.第二步,迭代属性,克隆我们的模板,然后添加到 DOM。

 //Get the template var template = document.getElementById("inventoryItem"); function showOptions() { /*let userPicked = document.getElementById("list").value; var div = document.getElementById("div"); if(userPicked == 'one'){ div.innerHTML = (electronics.store); }else{ alert("You must select a store."); }*/ document.querySelector("#store .storeName").innerHTML = electronics.store; generateInventory(document.querySelector("#store .laptops > ul"), electronics.inventory.Laptops); generateInventory(document.querySelector("#store .computers >ul"), electronics.inventory.Computers); } function generateInventory(node, object) { //Iterate the properties for (var itemName in object) { if (Object.prototype.hasOwnProperty.call(object, itemName)) { let item = object[itemName]; //Clone the template let clone = template.content.cloneNode(true); //Populate the content clone.querySelector(".brand").textContent = item.brand; clone.querySelector(".cost").textContent = clone.querySelector(".cost").textContent + item.cost; //Append to the DOM node.appendChild(clone); } } } let electronics = { store: "Mike's Computers", inventory: { "Laptops": { 0: { brand: "iMac", cost: 2000 }, 1: { brand: "Dell", cost: 600 } }, "Computers": { 2: { brand: "Windows PC", cost: 1300 } } } }; showOptions();
 #store ul { list-style: none; padding-left: 0; } #store ul ul { padding-left: 1em; }
 <div id="store"> <h1 class="storeName"></h1> <ul class="inventory"> <li class="laptops"> <h2>Laptops</h2> <ul></ul> </li> <li class="computers"> <h2>Computers</h2> <ul></ul> </li> </ul> </div> <template id="inventoryItem"> <li> <div class="brand"></div> <div class="cost">$</div> </li> </template>

The code for duplicating the template is modified from: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template复制模板的代码修改自: https : //developer.mozilla.org/en-US/docs/Web/HTML/Element/template

You can iterate through the electronics store inventory with a for loop like so您可以像这样使用 for 循环遍历电子商店库存

for (let [key, value] of Object.entries(electronics))

Then in the body of the for loop, you can call the key and value and append it to the innerHTML like you are already doing above.然后在 for 循环的主体中,您可以调用键和值并将其附加到 innerHTML,就像您在上面所做的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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