我需要在 eBay 列表上用 javascript 显示相关产品。 我有这样的想法:我保留有关其他列表的数组信息,例如:该产品附加的网址、图像、价格和标签。
示例:
some_product = [
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
],
some_product_2 = [
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
]
在列表中我放置了如下代码:
<script type="text/javascript" src="http://domain.com/related_prod.js?keyword=home"></script>
我希望在“标签”中显示所有带有“主页”的产品。有人可以指导我找到解决方案吗?
最佳答案
首先,这不是有效的 JavaScript 或 JSON:
some_product = [
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
],
some_product_2 = [
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
]
上面的内容应该替换为对象的 { }
。
{
some_product: {
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
},
some_product_2: {
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
}
}
上面现在是一个 JavaScript 对象。但这已经变得更好了。现在,这是一个纯 JSON,必须将其添加到 JavaScript 变量中。考虑一下:
var products = {
some_product: {
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
},
some_product_2: {
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
}
}
现在使用products
,您可以循环并将其作为列表项。
var products = {
some_product: {
tags: 'home, garden, kitchen',
url: 'http://listing.url',
price: 100
},
some_product_2: {
tags: 'home, lifestyle, books',
url: 'http://listing2.url',
price: 120
}
}
var finalHtml = "";
for (var item in products) {
finalHtml += '<li><a href="' + products[item].url + '">' + item + '<\/a> <br \/>Tags: ' + products[item].tags + '<br \/>Price: ' + products[item].price + ' $</li>';
}
document.getElementById("products").innerHTML = finalHtml;
<ul id="products"></ul>
请参阅上面的代码片段。
关于javascript - 在javascript中显示相关产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34557714/