代码之家  ›  专栏  ›  技术社区  ›  Reynier

处理活动/非活动选项卡,还有其他更好的方法吗?

  •  0
  • Reynier  · 技术社区  · 11 年前

    我有两个选项卡,下面是这两个选项卡的HTML代码:

    <input type="button" value="Activos" id="tab-active" class="active">
    <input type="button" value="Inactivos" id="tab-inactive">
    

    我创建此代码以在选项卡之间进行更改:

    $("#tab-inactive").click(function() {
        var current = $(this);
    
        $("#tab-active").removeClass("active");
        current.addClass("active");
    
        $("#layout-center").load(Routing.generate('inactive_product'));
    });
    
    $("#tab-active").click(function() {
        var current = $(this);
    
        $("#tab-inactive").removeClass("active");
        current.addClass("active");
    
        $("#layout-center").load(Routing.generate('product_list'));
    });
    

    代码是有效的,但我想知道是否有更好的方法/路径可以做到这一点,是否有任何改进或围绕这一点的东西,以便优化和最小化代码

    2 回复  |  直到 11 年前
        1
  •  1
  •   Tomas Santos    11 年前

    稍微更改上面的代码。

    HTML格式

    <button type="button" value="inactive_product" class="tab active">Activos</button>
    <button type="button" value="product_list" class="tab">Inactivos</button>
    

    查询

    $('.tab').click(function() 
    {
        var $this         = $(this);
        var $tabs         = $('.tab');
        var route         = $this.val();
        var $layoutCenter = $("#layout-center");        
    
        $tabs.removeClass('active');
        $this.addClass('active');
    
        $layoutCenter.load(Routing.generate(route));  
    });
    
        2
  •  0
  •   u_mulder    11 年前

    例如:

    <input type="button" data-route="route1" value="Activos" class="tab active">
    <input type="button" data-route="route2" value="Inactivos" class="tab">
    
    $( ".tab" ).click(function() {
        var this$ = $( this );
        if ( !this$.hasClass( 'active' ) ) {
            $( '.tab.active' ).removeClass( 'active' );
            this$.addClass( 'active' );
            $( "#layout-center" ).load( Routing.generate( this$.data( 'route' ) ) );
        }
     } );
    

    万一 仅限2个选项卡 即使 toggleClass( 'active' ) 可以使用。