显示与父级具有相同类的图像,该类与列表项的ID相同



>JSFIDDLE<lt

var imgFilterBtn = $("nav > ul > li > ul > li > a");
$("img").fadeIn("slow");
imgFilterBtn.click(function() {
    var fadeInClass = $(this).attr("id");
    var wrongFilter = $(this).parent("li").parent("ul").children("li").children("a");
    wrongFilter.removeClass(); // un-style all links in one sub-list
    $(this).toggleClass("selected"); // style selected link

    var wrongFilterID = wrongFilter.attr("id");
    $("#imgWrap").removeClass(wrongFilterID); // remove all classes from imgWrap that are equal to an ID all LI-items in  the current list

    $("#imgWrap").toggleClass(fadeInClass); // toggle the class that is equal to the ID of the clicked a-element
    $("img").hide(); // hide all images
    var imgWrapClass = $("#imgWrap").attr("class");
    $("#imgWrap").children("img." + imgWrapClass).fadeIn("fast"); // fade in all elements that have the same class as imgWrap
});   

我已经尽我最大的努力加入评论,解释脚本正在做什么。

1.工作原理:

  • 加载文档时图像会淡入
  • "选定"类被切换(但未切换为BACK!)
  • #imgWrap上的类被切换,但不会被切换回
  • 单击列表项(实际上是其父项li)时,图像将被隐藏并显示

2.什么不起作用

  • 当单击li项目时,其他类不会被删除
  • 上面提到的事情

3.该怎么办当用户单击链接时,该链接的ID将传递给分配给#imgWrap的类。但是,在分配该类之前,与同一列表(因此不是另一列表)的其他列表项的ID相同的所有其他类都将被删除。因此,当您单击blackfashion,然后单击brown时,#imgWrap应该具有类fashionbrown,并且black应该已被删除。

我猜我错过了一个each函数,但我不确定。

问题似乎是wrongFilter包含该特定列表的所有a元素,而wrongFilter.attr("id")始终选择第一个所选元素的ID。

关于切换:如果选择了已经选择的元素,则首先删除selected类,然后再次添加它。类似于添加到#imgWrap的类。

将选择限制为实际选择的元素,并修复类添加/删除:

// ...
// Only get the currently selected element
var wrongFilter = $(this).closest('ul').find('a.selected');
var wrongFilterID = wrongFilter.attr("id"); // get its ID
// toggle `selected` for the previous selected element and the current one;
// will remove the class if the previous selected element is the same as the
// current one 
wrongFilter.add(this).toggleClass('selected');
// ...
// if the class already exists, the same menu entry was clicked and we have 
// to remove the class
$("#imgWrap").toggleClass(fadeInClass, wrongFilterID !== fadeInClass);
// ...

但现在可以是wrongFilterIDundefined,并且对removeClass的下一个调用将从#imgWrap中移除所有类。所以你必须添加一个测试:

if(wrongFilterID) {
    $("#imgWrap").removeClass(wrongFilterID); 
}

另一个问题是,imgWrapClass可以是以空间分隔的类字符串,例如"fashion black",这意味着

.children("img." + imgWrapClass)

将导致

.children("img.fashion black")

这不是你想要的。

您必须从该字符串中创建一个合适的选择器,例如:

// "fashion black" becomes "fashion.black"
var imgWrapClass = $.trim($("#imgWrap").attr("class")).replace(/s+/g, '.');

修复了所有这些之后,它似乎可以正常工作:

DEMO

最新更新