如何简化下面的函数

How do I simplify the function below?

本文关键字:函数 何简化      更新时间:2023-09-26

我用下面的代码块实现了一个内容切换器,但我正在寻找一种简化它的方法。有多达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/

我希望这能有所帮助。