【问题标题】:How do I simplify the function below?如何简化下面的功能?
【发布时间】:2014-04-10 21:56:38
【问题描述】:

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

【问题讨论】:

  • 你能用一个简化的例子做一个 jsfiddle 吗?如果没有与脚本相关的标记,这很难解码。

标签: javascript jquery performance jquery-ui


【解决方案1】:

从您的代码看来,您正在使用#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/

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多