我正在创建一个虚构的在线吉他商店。我的主页上有一个图像轮播,我希望能够单击图像并重定向到产品页面,其中包含有关单击的项目、单击的图像和三个附加图像的信息。
我知道如何重定向到页面,我知道如何动态加载图像(图库已通过这种方式消失),但在两个文件之间工作时我似乎无法同时完成这两项工作。现在我的产品页面图像是硬编码的。
这是我要添加新图像 src 的 div。我可以这样做或者动态创建一个新的 img 标签,没关系
<div class="product-img-focus">
<img id="clickImg" class="img-fluid" src="../../img/sale/gibson/295-1.jpg" alt="guitar1">
</div>
这是我一直在研究的代码。我留下了注释行,这样你就可以看到我一直在尝试什么。基本上,当单击的 src 与 json 文件中的 img1 src 之一匹配时,我希望加载该对象的图像。现在我只关心 img1
$(".more-info").on("click", function(e) {
let moreSrc = $(e.target).attr('src')
$.getJSON("../json/guitars.json", function(json) {
var more_info = '';
for(var i in json) {
if (moreSrc === json[i].img1 ) {
var image1 = json[i].img1
var image2 = json[i].img2
var image3 = json[i].img3
var image4 = json[i].img4
var alt = json[i].alt
more_info += `<img id="clickImg" class="img-fluid" src="${image1}" alt="${alt}">`
// console.log(moreSrc)
// console.log(json[i].img1)
// window.location.href = "./pages/html/product.html";
// $('#clickImg').attr('src', moreSrc);
}
}
$('.product-img-focus').html(more_info)
window.location.href = "./pages/html/product.html"
})
})
json 示例
{
"category": "1",
"condition": "used",
"justIn": "true",
"brand": "Gibson",
"year": "1952",
"code": "456def",
"img1": "../img/sale/gibson/295-1.jpg",
"img2": "../img/sale/gibson/295-2.jpg",
"img3": "../img/sale/gibson/295-3.jpg",
"img4": "../img/sale/gibson/295-4.jpg",
"alt": "guitar1",
"title": "Gibson ES-295 1952",
"price": "$6,000.00",
"description": "A beautiful ES-295 with wear you can't fake! The ES-295 was originally produced from 1952 to 1958 and is best known for being the model played by Scotty Moore with Elvis. This particular example plays well with a fantastic feeling neck! The guitar has heavy finish wear with the beautiful greening that you often see on '50s goldtops. Glaser has refretted the guitar and replaced the tailpiece crossbar. The pickguard is missing.",
"specs": ["Body Wood - Laminated Maple",
"Neck Wood - Mahogany",
"Fingerboard Wood - Rosewood",
"Scale Length - 24.75",
"Nut Width - 1 11/16",
"Pickup(s) - Original P-90s",
"Case - Hard Case"
]
},
JQuery 或 vanilla JS 都可以。在发帖之前我到处搜索。谢谢!
最佳答案
您将需要一种方法来告诉新页面要显示什么图像。我会尝试使用 URL parameter 传递该信息.
也许是这样的:
window.location.href = "./pages/html/product.html?item=img1"
然后,在产品页面上,加载 JSON 并将 URL 参数用作对象键。
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var guitar = getUrlVars()["item"];
...
$('#clickImg').attr('src', '../' + guitar;
关于javascript - 单击图像并重定向到新页面,并将单击的图像动态添加到新页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59491866/