如何在Bootstrap列表项上添加活动类并从其他列表中删除活动类?

时间:2014-11-09 20:44:30

标签: jquery html angularjs twitter-bootstrap

我有以下HTML代码:

<a href="" ng-ctrl="ThemesCtrl" ng-click="checkThemeContent(theme)" ng-repeat="theme in themes" ng-hide="theme[filterProp] !== filterValue" class="list-group-item ng-scope">
    <b class="ng-binding">Test</b>
    <span class="themesListIcons ng-binding">
        <i class="fa fa-check-square-o"></i> 0
        <i class="fa fa-comment-o"></i> 2
    </span>
</a>

我希望在点击将活动类添加到项目所选项目后,从列表中的所有其他项目中删除活动类。

我试图通过这种方式做到这一点:

// Set active list item
$('a.list-group-item').click(function() {
    alert('test');
    $(this).parent().addClass('active').siblings().removeClass('active');
});

但它不起作用。

有人能告诉我怎么能以正确的方式做到这一点?

使用AngularJS或jQuery。

2 个答案:

答案 0 :(得分:2)

这可能为时已晚,但其他人会觉得这很有用。在您的jQuery代码中,您将向父级添加“活动”类。

使用Bootstrap和jQuery,您必须使用以下代码。

引导程序(Div结构):

<div class="list-group">
    <a href="#" class="list-group-item">
        Item 1
    </a>
    <a href="#" class="list-group-item">
        Item 2
    </a>
</div>

jQuery:

jQuery("a.list-group-item").click(function (e) {
    jQuery(this).addClass('active').siblings().removeClass('active');
});

答案 1 :(得分:-1)

尝试这种方式:

 // Set active list item 
 $('a.list-group-item').click(function() {
    alert('test');

    $(this).parent().parent().find('.active').removeClass('active');

    // or 

    $(this).closest('ul').find('.active').removeClass('active');

    $(this).parent().addClass('active');
 });

您必须找到活动元素,删除“活动”类,然后才将其添加到新项目中。 目前,您正在为新元素设置活动类,然后将其从所有人中删除。

编辑: 刚注意到角标签.. 你绝对应该使用ng-class属性,并尽可能避免声明你自己的点击处理程序。

<a ... ng-class="{active:theme == currentTheme}" ng-click="checkThemeContent(theme);currentTheme=theme" ..>
相关问题