我试图仅显示ALT与颜色样本(产品变体)相同的产品的产品缩略图,您可以点击它们。通常,您会在Shopify中看到所有产品变体的所有图像。我做了一个非常长的代码,但是我想让它更好地维护,所以我做了一个循环。好吧,这个循环不起作用,但我无法弄清楚它为什么不起作用。任何人都可以看到问题吗?
这是不工作的代码
// Only display the images from the first color variant
var getAltName = document.getElementsByClassName('thumbnail')[0].alt;
var imageAlt = '[alt="' + getAltName + '"]';
$('.thumbnail').not(imageAlt).css("display", "none");
var colorSwatchesArray = ["red","navy","pink","black","cobalt","yellow","white"];
for (var i = 0; i < colorSwatchesArray.length; i++) {
var imageAltLoop = '[alt="' + colorSwatchesArray[i] + '"]';
var imageClassLoop = colorSwatchesArray[i];
$("." + imageClassLoop).click(function(){
$('.thumbnail').not(imageAltLoop).css("display", "none");
$(imageAltLoop).css("display", "block");
});
}
这是WORKS
的代码 // When you go to the product page, only show the product images (thumbnails) which has the ALT tag that the first product image has
var getAltName = document.getElementsByClassName('thumbnail')[0].alt;
var imageAlt = '[alt="' + getAltName + '"]';
$('.thumbnail').not(imageAlt).css("display", "none");
// red - Click on the color swatch and show all thumbnails whiteh the same ALT tag, and hide all thumbnails which hasn't the same ALT tag as the color swatch
$(".red").click(function(){
$('.thumbnail').not('[alt="red"]').css("display", "none");
$('[alt="red"]').css("display", "block");
});
// Navy
$(".navy").click(function(){
$('.thumbnail').not('[alt="navy"]').css("display", "none");
$('[alt="navy"]').css("display", "block");
});
// Pink
$(".pink").click(function(){
$('.thumbnail').not('[alt="pink"]').css("display", "none");
$('[alt="pink"]').css("display", "block");
});
// black
$(".black").click(function(){
$('.thumbnail').not('[alt="black"]').css("display", "none");
$('[alt="black"]').css("display", "block");
});
// Cobalt
$(".cobalt").click(function(){
$('.thumbnail').not('[alt="cobalt"]').css("display", "none");
$('[alt="cobalt"]').css("display", "block");
});
// yellow
$(".yellow").click(function(){
$('.thumbnail').not('[alt="yellow"]').css("display", "none");
$('[alt="yellow"]').css("display", "block");
});
// White
$(".white").click(function(){
$('.thumbnail').not('[alt="white"]').css("display", "none");
$('[alt="white"]').css("display", "block");
});
答案 0 :(得分:0)
问题在于你添加的循环,以及你在循环中初始化变量然后在click事件处理程序中使用它们的事实。虽然这似乎是完全符合逻辑的,但是当点击事件处理程序被触发时,变量将全部改变。
这是一个简单的修复方法 - 只需将代码中的代码包装在一个匿名函数中,这样所有变量只有局部范围,不能在函数外部受到影响......
for (var i = 0; i < colorSwatchesArray.length; i++) {
(function() {
var imageAltLoop = '[alt="' + colorSwatchesArray[i] + '"]';
var imageClassLoop = colorSwatchesArray[i];
$("." + imageClassLoop).click(function(){
$('.thumbnail').not(imageAltLoop).css("display", "none");
$(imageAltLoop).css("display", "block");
});
})();
}