如何简化下面的函数
How do I simplify the function below?
我用下面的代码块实现了一个内容切换器,但我正在寻找一种简化它的方法。有多达10个或更多的主题需要切换,我如何简化它,使代码不会太大,而不是每个div都有一个代码块。
jQuery(document) .ready(function () {
$('.topic-intro:not(:nth-of-type(1))') .hide();
$('#mid-nav-in ul li:nth-of-type(1)') .addClass('active');
$('#mid-nav-in ul li a:nth-of-type(1)') .click(function () {
$('.topic-intro:not(:nth-of-type(1))') .hide();
$('.topic-intro:nth-of-type(1)') .show();
$('#mid-nav-in ul li:not(:nth-of-type(1))') .removeClass('active');
$('#mid-nav-in ul li:nth-of-type(1)') .addClass('active');
});
});
jQuery(document) .ready(function () {
$('#mid-nav-in ul li:nth-of-type(2) a') .click(function () {
$('.topic-intro:not(:nth-of-type(2))') .hide();
$('.topic-intro:nth-of-type(2)') .show();
$('#mid-nav-in ul li:nth-of-type(2)') .addClass('active');
$('#mid-nav-in ul li:not(:nth-of-type(2))') .removeClass('active');
});
});
从您的代码中可以看出,您正在使用#mid-nav-in
中的链接来显示相应的.topic-intro
,然后隐藏所有其他链接。代码还取决于.topic-intro
元素的顺序与#mid-nav-in
中的链接的顺序相同。如果是这种情况,下面这样的东西会起作用:
$('#mid-nav-in li a').on('click', function(){
// Remove 'active' Class from all <li/>
$('#mid-nav-in li').removeClass('active');
// Add 'active' Class to <li/> of Clicked Link
$(this).closest('li').addClass('active');
// Hide All .topic-intro elements
$('.topic-intro').hide();
// Show .topic-intro element at the Same index of Clicked Link
$('.topic-intro').eq($(this).closest('li').index()).show();
return false; // prevent default action
});
// Automatically Select the First Link
$('#mid-nav-in li a').eq(0).trigger('click');
下面是一把小提琴作为例子:http://jsfiddle.net/6hd97/2/
我希望这能有所帮助。
相关文章:
- 使用element简化onclick函数
- 如何简化jquery动画函数代码
- 使用命名的自调用函数简化代码
- 简化在 CasperJS 中映射多个子元素以仅使用一个函数
- 用重复的相似行简化 javascript 函数(带有循环?
- jQuery.queue() 与使用回调函数完成某事有何不同
- 最新版本的 Typescript 中是否有任何内容可以简化函数链
- 使用用于在同一函数中命名函数的变量名称有何意义
- $scope函数参数从何而来
- 在 JavaScript 中命名匿名函数有何不同
- 简化函数,这样代码就不会变得太大
- 有没有一个Javascript函数可以简化混合分数
- 简化了两个变更函数调用jquery
- 简化我的函数(循环、数组)
- 简化随机订单jQuery函数
- 简化工作函数以替换特定单词
- 如何在导航栏函数中简化jQuery
- 函数用于简化jquery中的代码
- Javascript显示图像函数:帮助简化函数
- 通过编写适当的 JavaScript 函数来简化我的代码