<强>>>强> 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。什么有效:
- 图像在文档加载时淡入
- “选定”类别已切换(但未切换回来!)
- 类(class)
#imgWrap
已切换,但不会切换回来 - 当单击列表项(实际上是其父项
li
)时,图像会隐藏并显示
<强>2。什么不起作用
- 当点击某个 li-item 时,其他类不会被删除
- 上面提到的事情
<强>3。应该发生什么
当用户单击链接时,该链接的 ID 会传递到分配给 #imgWrap
的类。 。但在分配此类之前,与同一列表(因此不是另一个列表)的其他列表项的 ID 相同的所有其他类都会被删除。因此,当您单击black
时和fashion
,然后 brown
#imgWrap
应该有类(class) fashion
和brown
,和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);
// ...
但现在可能是 wrongFilterID
是 未定义
,并且下一次调用 removeClass
会删除 #imgWrap< 中的所有类
。所以你必须添加一个测试:
if(wrongFilterID) {
$("#imgWrap").removeClass(wrongFilterID);
}
另一个问题是 imgWrapClass
可以是空格分隔的类字符串,例如“时尚黑”
,这意味着
.children("img." + imgWrapClass)
将导致
.children("img.fashion black")
这不是你想要的。
您必须从该字符串创建一个正确的选择器,例如:
// "fashion black" becomes "fashion.black"
var imgWrapClass = $.trim($("#imgWrap").attr("class")).replace(/\s+/g, '.');
<小时/>
完成所有这些修复后,它似乎可以正常工作:
关于jquery - 显示与父级相同类的图像,与列表项的 ID 相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11399102/