显示与父级相同的图像,与list-item的ID相同

时间:2012-07-09 16:18:01

标签: jquery toggle each

>> JSFIDDLE <<

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。什么有效:

  • 图像淡入文档加载
  • 切换“选定”类(但不切换回来!)
  • #imgWrap上的课程已切换,但未切换回来
  • 图片被隐藏,并在点击列表项(实际上是其父li)时显示

2。什么行不通

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

第3。应该怎么做 当用户单击链接时,链接的ID将传递给分配给#imgWrap的类。但是在分配此类之前,所有其他类与同一列表的其他列表项的ID相同(因此不是另一个列表的ID)将被删除。因此,当您点击blackfashion,然后brown #imgWrap应该有fashionbrown,以及{{1}应该已被删除。

我猜我错过了black函数,但我不确定。

1 个答案:

答案 0 :(得分:2)

问题似乎是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