如何简化下面的功能?

时间:2014-04-10 21:56:39

标签: javascript jquery performance jquery-ui

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

1 个答案:

答案 0 :(得分:3)

您的代码中显示您使用#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/

我希望这会有所帮助。

相关问题