>> 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。什么行不通
第3。应该怎么做
当用户单击链接时,链接的ID将传递给分配给#imgWrap
的类。但是在分配此类之前,所有其他类与同一列表的其他列表项的ID相同(因此不是另一个列表的ID)将被删除。因此,当您点击black
和fashion
,然后brown
#imgWrap
应该有fashion
和brown
,以及{{1}应该已被删除。
我猜我错过了black
函数,但我不确定。
答案 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);
// ...
但现在可能wrongFilterID
为undefined
,下一次调用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, '.');
完成所有修复后,它似乎正常工作: