我在这里遇到了类似的问题: jQuery function for specific class 我解决了。但它让我很烦恼,因为它有太多的 div,而且看起来不太好,所以我重写了我的 HTML 代码并重写了选择器脚本。 现在脚本可以很好地加载图像(它将它们全部淡入)但是选择根本不起作用。 我尝试使用 closest 和 siblings 函数,但无济于事。
我该如何解决这个问题? 您可以在以下位置找到相关页面: http://baldino.rs/baby-program/
提前致谢
$(document).ready(function(){
var picture = $('.post-cipela').each(function(index, element) {
$(this).find('.cipela-bg img:eq(0)').fadeIn(500);
$('.colorwrap a').click(function(){
var index = $(this).find(".colorwrap a").index(this);
$('.cipela-bg img').fadeOut(200);
$('.cipela-bg img:eq('+index+')').fadeIn(500);
});
});
编辑-1: 我修改了我的脚本。现在我遇到了一个问题,因为我的图像多次淡入淡出。我该如何解决? - 这是修改后的脚本,您可以看到问题的页面在这里: http://baldino.rs/baby-program
$(document).ready
(
function()
{
$(".cipela-1").fadeIn(200);
$(".colorwrap a").click
(
function()
{
var item = $(this);
var a = item.attr("rel");
item.closest(".post-cipela").find(".cipela-1, .cipela-2, .cipela-3, .cipela-
4").fadeOut(200);
item.closest(".post-cipela").find("."+a).first().fadeIn(200);
}
);
}
);
最佳答案
你粘贴的代码是恶意的,你有一个额外的 });
在最后。
此外,您将 $('.colorwrap a') 选择器包装在 .each
函数循环中,我不确定您是不是这个意思。
此外,您还遗漏了一些有关 this 变量范围的信息。
each
中的这一行没问题。
$(this).find('.cipela-bg img:eq(0)').fadeIn(500);
然后你实例化一个点击处理程序
$('.colorwrap a').click(function(){
var index = $(this).find(".colorwrap a").index(this);
该处理程序中的 $(this) 指的是 .colorwrap
中匹配的 a
。然后你会在它下面找到另一个 .colorwrap a
的实例,它可能不存在,因此你的选择器找不到任何东西。
如果您确实打算在每次迭代中包装此点击处理程序,您应该将 $(this)
分配给循环中的一个变量,并在点击处理程序中使用它,如下所示
var picture = $('.post-cipela').each(function(index, element) {
var that =$(this);
that.find('.cipela-bg img:eq(0)').fadeIn(500);
$('.colorwrap a').click(function(){
var index = that.find(".colorwrap a").index(this);
$('.cipela-bg img').fadeOut(200);
$('.cipela-bg img:eq('+index+')').fadeIn(500);
});
});
关于jquery - jQ 图像选择器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10543781/