JS:单击数组中的对象

时间:2018-12-11 08:00:27

标签: javascript html

我有一个包含在HTML中的对象数组。 我必须能够点击<a href='#' class='addToCart'>Order</a> 并将单击的对象数据添加到我的console.log(“ ...”);。

做到这一点的最佳方法是什么?

摘要:

"use strict";

document.addEventListener('DOMContentLoaded', loadMeals);

const meals = [
    {
        id: 1,
        title: 'Strawberry Salad with Poppy Seed Dressing',
        img: 'Strawberry-Salad-with-Poppy-Seed-Dressing.jpg',
        book: 1,
        calories: 298,
        servings: 3,
        type: 'lunch',
        price: 15,
        cook: 'Jenny Jefferson',
        quantity: 10,
    },
    {
        id: 2,
        title: 'Cashew Turkey Salad Sandwiches',
        img: 'turkey-sandwich.jpg',
        book: 2,
        calories: 198,
        servings: 2,
        type: 'lunch',
        price: 9,
        cook: 'Jenny Jefferson',
        quantity: 10
    }
];


function loadMeals() {
    let i = 0;
    let id = 1;
    let fillMealList = document.querySelector("#fillMealList");
    for (let i = 0; i < meals.length; i++) {
        let item = meals.find(item => item.id === id);
        fillMealList.innerHTML +=
            "<article>"+
            "<h3>" + item.title + "</h3>"+
            "<figure>"+
            "<img src='images/" + item.img + "'" +">" +
            "<figcaption>"+
            "Meal by: " +"<span>" + item.cook + "</span>" +
            "</figcaption>" +
            "</figure>"+
            "<div class='info'>"+
            "<p>€ <span>" + item.price + "</span>" + "/pp" + "</p>" +
            "<a href='#' class='addToCart'>Order</a>"+
            "</div>"+
            "</article>";
        id++;
    }
}
<div id="mealList">
            <div class="flexcontainer" id="fillMealList"></div>
            </div>

2 个答案:

答案 0 :(得分:1)

您只需将onclick事件添加到<a>标签:<a class="addToCart" onclick="addToCart(item)">order</a>

然后定义函数addToCart()

function addToCart(item) {              
console.log(item)
}

答案 1 :(得分:1)

如下更改超链接HTML:

"<a href='javascript:logMeal(" + item.id + ")' class='addToCart'>Order</a>"+

并添加一个名为logMeal的新函数,如下所示:

function logMeal(id) {
    console.log(meals.find(item => item.id === id));
}