jQuery简化
我正在为一个网站编写一些代码,该网站使用4个列表项来显示/隐藏页面上不同位置的4个不同的div。
这是我正在做的一个粗略的例子:
- One
- Two
- Three
- Four
This is the first div This is the second div This is the third div This is the four div
而且我有一些丑陋的JS代码正在进行中,对于我的生活,我不记得/弄清楚如何简化它。
$("#first").click(function() { $("#one").fadeIn(); $("#two, #three, #four").fadeOut(); }); $("#second").click(function() { $("#two").fadeIn(); $("#one, #three, #four").fadeOut(); }); $("#third").click(function() { $("#three").fadeIn(); $("#two, #one, #four").fadeOut(); }); $("#fourth").click(function() { $("#four").fadeIn(); $("#two, #three, #one").fadeOut(); });
这就是我所需要的,但我知道必须有一种更简单的方法。 这是一个工作的JSFiddle – http://jsfiddle.net/claycauley/FBrx5/
如果任何人可以帮助我理解为什么/如何简化它也会很好,因为我正在努力学习但却难以理解。
尝试:
$("li").click(function() { $("div:visible").fadeOut(); $("div").eq($(this).index()).fadeIn(); });
在@Petah的帮助下,我想出了这个:
$("li").click(function() { if ($("div").eq($(this).index()).is(":visible")) { return false; } else { $("div:visible").fadeOut(); $("div").eq($(this).index()).fadeIn(); } return false; });
他的解决方案唯一的问题是它仍然在div上激活,即使它已经可见。 它会消失,然后重新进入。有了这个,我可以阻止它发生。
怎么样的:
- One
- Two
- Three
- Four
This is the first div This is the second div This is the third div This is the four div $("#linky").on("click", "li", function(e) { $("div:visible").fadeOut(); $("." + e.target.id).fadeIn(); });