gpt4 book ai didi

Javascript - 使用 "data-id"获取对象的属性并在元素上打印

转载 作者:行者123 更新时间:2023-11-30 13:18:42 25 4
gpt4 key购买 nike

我试图从这个数组中选择一个对象,并使用“data-id”将其所有属性打印到一个元素中。我该怎么做呢?另外,如何为新的 CarObjects 提供 ID?

**<div id="carInfo" data-id="10"></div>**

function Car(company, name, price, details, image, alt){
this.company = company;
this.name = name;
this.price = price;
this.details = details;
this.image = image;
this.alt = alt;
}

var carInformation = [new Car("Ferrari", "Marenello", " $250,000", "Fast. Very Fast.", "images/ferrari.jpg","image of ferrari"),
new Car("Dodge", "Viper", " $100,000","Great Acceleration","images/dodge.jpg", "image of viper"),
new Car("Ford", "Shelby", "$80,000", "Muscle Car", "images/mustang.jpg", "image of mustang"),
new Car("Back To The Future", "Delorean", "$20,000", "Travels through time","images/delorean.jpg", "image of delorean"),
new Car("Lamborghini", "Diablo", "$250,000", "Fastest","images/lambo.jpg","image of lamborghini"),
new Car("CMercedes Benz", "SLR", "$180,000", "Classy Vehicle.","images/benz.jpg","image of mercedes benz"),
new Car("Chevrolet", "Corvette", "$70,000", "Fiberglass body Light Vehicle.","images/vette.jpg","image of corvette"),
new Car("Porsche", "Carrera", "$120,000", "Great Handling.","images/porsche.jpg", "image of porsche"),
new Car("Audi", "R8", "Price: $110,000", "Fast and Classy.", "images/audi.jpg","image of audi") ];

最佳答案

jQuery 允许您通过 data() 获取 data-id 属性方法;

var carInfo = carInformation[$('#carInfo').data('id')];

Object.keys(carInfo).forEach(function (val) {
console.log(val + " is " + this[val]);
}, carInfo);

上面的代码片段使用了 ECMAScript5 specification 中的代码,即 not supported in older browsers .如果你想支持他们,你需要使用 ES5 shimpolyfiller ,或使用以下代码段:

var carInfo = carInformation[$('#carInfo').data('id')];

for (var x in carInfo) {
if (carInfo.hasOwnProperty(x)) {
console.log(x + " is " + carInfo[x]);
}
}

将其打印到元素中取决于您希望它如何格式化,但上面的代码将为您提供执行此操作所需的所有详细信息。

编辑:请记住,您的 carInformation 数组中只有 8 个元素...

关于Javascript - 使用 "data-id"获取对象的属性并在元素上打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11101310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com