简体   繁体   English

如何在 HTML 中显示来自 JS Object 的信息?

[英]How do I display information from JS Object in HTML?

How can I create something like this:我怎样才能创建这样的东西: 在此处输入图像描述

I already have JS objects stored like this:我已经有这样存储的 JS 对象:

var hoodieArray = [{
    type: 'Hoodie',
    color: 'Purple',
    material: 'cotton authentic',
    price: '£39.99',
    image: 'images/items/hoodies/hoodie (1).jpg'
},
{
    type: 'Hoodie',
    color: 'Light Blue',
    material: 'cotton authentic',
    price: '£39.99',
    image: 'images/items/hoodies/hoodie (2).jpg'
},
{
    type: 'Hoodie',
    color: 'Green',
    material: 'cotton authentic',
    price: '£39.99',
    image: 'images/items/hoodies/hoodie (3).jpg'
}]

but I'm not entirely sure how to display them in a product card.但我不完全确定如何在产品卡片中显示它们。 here's what I have made so far:这是我到目前为止所做的:

<style>
    .card {
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
        max-width: 300px;
        margin: auto;
        text-align: center;
    }

    .price {
        color: grey;
        font-size: 22px;
    }

    .card button {
        outline: 0;
        color: #000000;
        text-align: center;
        font-size: 18px;
    }
</style>

<div class="card">
    <img src="https://img.sonofatailor.com/images/customizer/product/White_O_Crew_Regular_NoPocket.jpg" alt="Denim Jeans" style="width:100%">
    <h1>Tailored Jeans</h1>
    <p>Some text about the jeans..</p>
    <p class="price">$19.99</p>
    <p><button>Add to Cart</button></p>
</div>

which displays this:显示:

在此处输入图像描述

How would you approach this?你会如何处理这个问题? as I want them to be displayed next to each other properly with their respective information provided in the JavaScript Object因为我希望它们正确地彼此相邻显示,并在 JavaScript Object 中提供各自的信息

You need javascript for this.为此,您需要 javascript。

First of all you need to create a container to contain all the cards首先,您需要创建一个容器来包含所有卡片

<div id="hoodiesContainer" style="display: flex; justify-content: space-between; margin: 30px;">

</div>

Then you have to evaluate the hoodieArray to get all elements to display in the cards:然后您必须评估hoodieArray以使所有元素显示在卡片中:

var hoodieArray = [{
    type: 'Hoodie',
    color: 'Purple',
    material: 'cotton authentic',
    price: '£39.99',
    image: 'images/items/hoodies/hoodie (1).jpg'
},
{
    type: 'Hoodie',
    color: 'Light Blue',
    material: 'cotton authentic',
    price: '£39.99',
    image: 'images/items/hoodies/hoodie (2).jpg'
},
{
    type: 'Hoodie',
    color: 'Green',
    material: 'cotton authentic',
    price: '£39.99',
    image: 'images/items/hoodies/hoodie (3).jpg'
}]

//Evaluate each hoodie and display its details
    hoodieArray.forEach(function (hoodie) {
        let card = `
        <div class="card">
            <img src="${hoodie.image}" style="width:100%">
            <h1>${hoodie.material}</h1>
            <p>Color: ${hoodie.color}</p>
            <p class="price">${hoodie.price}</p>
            <p><button>Add to Cart</button></p>
        </div>
    `;
        // Add the card to the page
        document.getElementById('hoodiesContainer').innerHTML += card;
    });

Put together as a runnable snippet...放在一起作为一个可运行的片段......

 var hoodieArray = [{ type: 'Hoodie', color: 'Purple', material: 'cotton authentic', price: '£39.99', image: 'images/items/hoodies/hoodie (1).jpg' }, { type: 'Hoodie', color: 'Light Blue', material: 'cotton authentic', price: '£39.99', image: 'images/items/hoodies/hoodie (2).jpg' }, { type: 'Hoodie', color: 'Green', material: 'cotton authentic', price: '£39.99', image: 'images/items/hoodies/hoodie (3).jpg' }, { type: 'Hoodie', color: 'Dark Gary', material: 'cotton authentic', price: '£39.99', image: 'images/items/hoodies/hoodie (4).jpg' }, { type: 'Hoodie', color: 'Light Gary', material: 'cotton authentic', price: '£39.99', image: 'images/items/hoodies/hoodie (4).jpg' }, ] // Evaluate each hoodie and display its details hoodieArray.forEach(function (hoodie) { let card = ` <div class="card"> <img src="${hoodie.image}" style="width:100%"> <h1>${hoodie.material}</h1> <p>Color: ${hoodie.color}</p> <p class="price">${hoodie.price}</p> <p><button>Add to Cart</button></p> </div> `; // Add the card to the page document.getElementById('hoodiesContainer').innerHTML += card; });
 #hoodiesContainer { display: flex; flex-wrap: wrap; justify-content: space-between; margin: 30px; }.card { border: 1px solid gray; margin: 4px; }
 <div id="hoodiesContainer"> </div>

I did something like this in my website.我在我的网站上做了类似的事情。 In my accounts display (basically just user info, not actually an "account" account), the user data is in an individual JS object.在我的帐户显示中(基本上只是用户信息,实际上不是“帐户”帐户),用户数据位于单个 JS object 中。

Middle-click/Mouse-wheel-click/triple-finger-click the link https://majorflux.codehs.me/accounts.html and press CTRL + U and feel free to copy any snippets of my code.中键单击/鼠标滚轮单击/三指单击链接https://majorflux.codehs.me/accounts.html并按CTRL + U并随意复制我的代码片段。 You do not have to give credit, but you can if you want to.你不必给予信任,但如果你愿意,你可以。

What @Stephen_P said was for me to put the code itself instead of the link to it, so here it is: @Stephen_P 说的是让我放置代码本身而不是链接,所以这里是:

    <script>
        var d = {
            e: function(id){
                return(document.getElementById(id));
            },
            v: function(id){
                return(document.getElementById(id).value);
            },
            err: "data:image/svg+xml,%3Csvg%20id%3D'svgO'%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20width%3D'100px'%20height%3D'100px'%20viewbox%3D'0%200%20100%20100'%3E%0A%3Cpath%20d%3D%22M0%2C10%20L10%2C0%20L50%2C40%20L90%2C0%20L100%2C10%20L60%2C50%20L100%2C90%20L90%2C100%20L50%2C60%20L10%2C100%20L0%2C90%20L40%2C50%20Z%20M10%2C10%20L90%2C90%20M10%2C90%20L90%2C10%20M10%2C0%20L10%2C10%20L0%2C10%20M100%2C10%20L90%2C10%20L90%2C0%20M90%2C100%20L90%2C90%20L100%2C90%20M0%2C90%20L10%2C90%20L10%2C100%20M50%2C40%20L50%2C60%20M40%2C50%20L60%2C50%22%20fill-rule%3D%22nonzero%22%20fill%3D%22%23ff0000%22%20stroke%3D%22%23ffaa00%22%2F%3E%0A%3C%2Fsvg%3E"
        };
        var users = {
            "Major_Flux": {
                icon: "https://lh3.googleusercontent.com/fife/AAWUweVYpHQn8eRcUjr22HSFuVDbV9VZiZ5GoV_2wApnhKXlGUPe_wqMUwlTGXcrLMtk7yvXobJc2aVOQWrfWxL-kp4GkE6ypKdkc4QfvjTU31RUJAtGenmqi9xvVa2heQ4I3LX6h18bYUZA6ZUljihgZKHmJQNaOcBp-6jnsMGFWwniQL4-I-EhM497HyShx_HmcHJ3dPw0Dw4jY1ZAfqMbaMTovQUKLGpmQNQHNth5xLIXN56C4CU7DNotb3t3epVNF66LWPfktQ4lrQuuvfQS2xn6QjJQ1kxkMCGR34Ersn73bmJ_6EwA9r5_OC0SJKgMmWwJS-k4MpEF3kcT_F2gnufmNFeSxY1yaa9zz4fx8mtSzQKxcs9T7APrcWMTDHEPCSZS_ezsUDy5KhBLkMol1plYD0PbjjuZVb6suEVAppZ70GYXtEhjv-X5_MH6qlVRstmgD_s26rFmfj9LgpNfWau9HpPRR0qwIikFGlqEEL4Ei_iOY0UjXyOmEZA661MVKPjZY7m7kjc6f_78l8fP0A9qOSc_AarZ2dM7BBkMqPRTaUE636GW9IN25T8jJY5YFyMlH1pqR4a1sJCDXdy-mmJqd4Zuu5diUQjgm0FzfsYfKkNzEa1UOzJENn9uLrkspdDzeTz4PrUV-caWrUH6Mq61txgMFnV8_sP104NEph42WUz5SBQ1bWN_KGTi0_x-IFWpFj38NiqyViOLN7eo7eaYqp7sKtz1EX7AvPZMiQ4mIA=s32-c",
                favorites: [{name: "Dredark.io", link: "https://test.drednot.io"},{name: "Junon.io", link: "https://junon.io"},{name: "Gunbox.io", link: "https://gunbox.io"},{name: "Grey Box Testing", link: "https://samhogan.itch.io/grey-box-testing"},{name: "Voxorp.io", link: "https://voxorp.io"}],
                friends: ["Minor_Flux"],
                about: "<pre>&Tab;</pre><p>Hi, I am an HTML + CSS + JS programmer. I have made this website on CodeHS's code editor. I have Autism and Sensory Processing Disorder, but I have succeeded my freshman year outside the supportive program. I got so good at coding that it has became my hobby. 2021 I am in my sophmore year of High School and so far I am doing good. Had been piling up with assignments a lot, but recovered on the week of Thanks Giving 2021. I have great strength in HTML, CSS, JavaScript, and SVG HTML, but only slightly advanced in AframeVR-augmented HTML.</p>",
                rank: "Developer"
            },
            "Minor_Flux": {
                icon: d.err,
                favorites: [{name: "Drawn To Life", link: "https://majorflux.codehs.me/404err.html"}],
                friends: ["Major_Flux"],
                about: "",
                rank: "Developer"
            }
        };
        var rankColors = {
            "Developer": "#00ff00",
            "User": "#008800"
        };
        var isNameApplicable = false;
        window.onload = function(){
            try{
                checkURI();
                loadUserList();
                setTimeout(() => {
                    if(isNameApplicable){
                        d.e("user-list").style.display = "none";
                    }
                },10);
            }catch(err){
                alert(err.stack);
            }
        };
        function loadUserList(){
            d.e("user-list").style.display = "block";
            for(var name in users){
                var user = users[name];
                var userBox = d.e("proto-user").innerHTML.replace(/!----/g,name).replace(/!-_--/g,user.icon).replace(/!__--/g,user.rank).replace(/!--_-/g,rankColors[user.rank]).replace(new RegExp("//!_---","g"),"window.location.replace('https://majorflux.codehs.me/accounts.html?user=" + name + "');");
                d.e("user-list").innerHTML += "&nbsp;" + userBox;
            }
        }
        function checkURI(){
            if(location.search){
                var x = location.search.substring(1).split("&");
                for(var i = 0; i < x.length; i++){
                    var y = x[i].split("=");
                    checkURIVal(y[0],y[1]);
                }
            }
        }
        function checkURIVal(name, value){
            if(name == "user"){
                openUser(value);
                isNameApplicable = true;
            }
        }
        function openUser(name){
            try{
                var userData = users[name];
                if(!userData){
                    isNameApplicable = false;
                    return(void(0));
                }
                d.e("icon").style.background = "url(" + userData.icon + ") no-repeat 50% 50%";
                d.e("name").innerHTML = name;
                document.title = name + "'s account";
                for(var i = 0; i < userData.favorites.length; i++){
                    var fav = userData.favorites[i];
                    var favbox = d.e("proto-res").innerHTML.replace(/!----/g,fav.name).replace(new RegExp("//!_---","g"),"window.open('" + fav.link + "')");
                    d.e("favorites").innerHTML += "&nbsp;" + favbox;
                }
                for(var i = 0; i < userData.friends.length; i++){
                    var friend = userData.friends[i];
                    var fdata = users[friend];
                    var fribox = d.e("proto-res").innerHTML.replace(/!----/g,friend).replace(new RegExp("//!_---","g"),"window.location.replace('https://majorflux.codehs.me/accounts.html?user=" + friend + "');");
                    d.e("friends").innerHTML += "&nbsp;" + fribox;
                }
                d.e("aboutme").innerHTML += userData.about;
            }catch(err){
                alert(err.stack);
            }
        }
    </script>

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

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